我想在uicollection View 上方放置一个搜索栏,如下图所示。我想以编程方式执行此操作。
ios - 如何使搜索栏在uicollectionview中工作-LMLPHP

目前看来

ios - 如何使搜索栏在uicollectionview中工作-LMLPHP

这是我的搜索栏设置功能代码。我在主 View Controller 中有它。

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)

}

最佳答案

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

这将以编程方式创建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
}()

接下来,在您的 View 中加载了注册头 View 。
collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerCellId")

覆盖以下方法,以定义 header 的高度。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: 40)
}

最后,将搜索栏添加到UICollectionview header 中,定义约束以适合整个 header View 。
    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
}

关于ios - 如何使搜索栏在uicollectionview中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44742957/

10-13 04:37