如何让搜索栏在uicollectionview中工作

时间:2017-06-25 03:33:24

标签: ios swift uicollectionview uisearchbar

我想在一个uicollection视图上方放置一个搜索栏,如下图所示。我想以编程方式执行此操作。 enter image description here

当前观点

my implementation

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

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)

} 

2 个答案:

答案 0 :(得分:3)

您可以将搜索栏添加到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
}()

接下来,在您的视图中,加载注册标题视图。

collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerCellId")

覆盖以下方法,以定义您希望标题的高度。

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

最后,将搜索栏添加到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
}

答案 1 :(得分: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