如何让搜索栏在uicollectionview中工作

jha*_*oo8 7 uisearchbar ios uicollectionview swift

我想在一个uicollection视图上方放置一个搜索栏,如下图所示.我想以编程方式执行此操作. 在此输入图像描述

目前来看

我的实施

这是我的搜索栏设置功能代码.我在家庭视图控制器中有它.

func setupSearchBar() {

    let searchBar = UISearchBar(frame: CGRect(x: 0, y: 64, width:UIScreen.main.bounds.width, height: 32))
    searchBar.barTintColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1)
    searchBar.backgroundColor = UIColor.blue
    searchBar.isTranslucent = true
    searchBar.placeholder = "Search Timeline"
    searchBar.searchBarStyle = UISearchBarStyle.prominent
    view.addSubview(searchBar)

} 
Run Code Online (Sandbox Code Playgroud)

ant*_*ash 5

您可以将搜索栏添加到UICollectionview标头中。

这将以编程方式创建searchBar

    lazy var searchBar : UISearchBar = {
    let s = UISearchBar()
        s.placeholder = "Search Timeline"
        s.delegate = self
        s.tintColor = .white
        s.barTintColor = // color you like
        s.barStyle = .default
        s.sizeToFit()
    return s
}()
Run Code Online (Sandbox Code Playgroud)

接下来,在您的视图中确实加载了标头视图。

collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerCellId")
Run Code Online (Sandbox Code Playgroud)

重写以下方法来定义您希望标头为的高度。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: 40)
}
Run Code Online (Sandbox Code Playgroud)

最后,将搜索栏添加到UICollectionview标头中,定义约束以适合整个标头视图。

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerCellId", for: indexPath)
        header.addSubview(searchBar)
        searchBar.translatesAutoresizingMaskIntoConstraints = false
        searchBar.leftAnchor.constraint(equalTo: header.leftAnchor).isActive = true
        searchBar.rightAnchor.constraint(equalTo: header.rightAnchor).isActive = true
        searchBar.topAnchor.constraint(equalTo: header.topAnchor).isActive = true
        searchBar.bottomAnchor.constraint(equalTo: header.bottomAnchor).isActive = true
    return header
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ieh 1

尝试添加这些代码:

    // Call sizeToFit() on the search bar so it fits nicely in the UIView
    self.searchController!.searchBar.sizeToFit()
    // For some reason, the search bar will extend outside the view to the left after calling sizeToFit. This next line corrects this.
    self.searchController!.searchBar.frame.size.width = self.collectionView!.frame.size.width
Run Code Online (Sandbox Code Playgroud)