gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:11:10 27 4
gpt4 key购买 nike

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

当前 View

my implementation

这是我的搜索栏设置功能代码。我在主视图 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")

覆盖以下方法以定义您希望页眉的高度。

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com