这是由于在 UISearchBarDelegate 方法内部调用了 reloadData()。解决此问题的一种方法是为包含搜索栏的标题视图专门设置一个额外的空白部分。然后代替 reloadData() 调用:
self.collectionView.reloadSections([1])
如果您没有多个数据部分,您可以通过加载虚假标题来消除第二个标题。
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if indexPath.section == 1 {
let fakeView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "fakeHeader", for: indexPath)
return fakeView
}
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: searchHeader, for: indexPath) as! SearchHeader
headerView.initializeHeader(with: self)
return headerView
}
接下来您可以将仿标题的高度设置为 0
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return section == 0 ? CGSize(width: collectionView.frame.width, height: 260) : CGSize(width: collectionView.frame.width, height: 0)
}
您将遇到的下一个问题将是单元格和第一个标题之间的间隙,这是由边缘插入引起的。所以消除第一部分的顶部和底部插图。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
if section == 1 {
return UIEdgeInsets(top: 20, left: 20, bottom: 30, right: 20)
}
return UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
}
希望这可以节省一些时间。