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