Swift 在滚动集合视图之前,ViewForSupplementalElementOfKind不会设置标签文本
我正在使用Swift 在滚动集合视图之前,ViewForSupplementalElementOfKind不会设置标签文本,swift,uicollectionview,collectionview,uicollectionreusableview,sectionheader,Swift,Uicollectionview,Collectionview,Uicollectionreusableview,Sectionheader,我正在使用viewforsupplementalelementofkind在我的集合视图中生成一个标题 标题(SectionHeader)是故事板中的一个章节标题附件,仅包含一个插座 class SectionHeader: UICollectionReusableView { @IBOutlet weak var sectionHeaderlabel: UILabel! } 下面是我的viewForSupplementalElementOfKind func collectionVi
viewforsupplementalelementofkind
在我的集合视图中生成一个标题
标题(SectionHeader
)是故事板中的一个章节标题附件,仅包含一个插座
class SectionHeader: UICollectionReusableView {
@IBOutlet weak var sectionHeaderlabel: UILabel!
}
下面是我的viewForSupplementalElementOfKind
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind:
String, at indexPath: IndexPath) -> UICollectionReusableView {
print("SECTION TITLE (brand of bindings) --------> \(sectionTitle)")
if let sectionHeader = allCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "bindingsID", for: indexPath) as? SectionHeader{
sectionHeader.sectionHeaderlabel.text = "Select \(sectionTitle)"
return sectionHeader
}
return UICollectionReusableView()
}
sectionTitle通过segue设置
问题在于加载此视图控制器时,标题为“选择”
当我从屏幕上滚动标题,然后返回屏幕时,标题会正确显示:“选择Burton绑定”
我测试了视图中的sectionTitle
,并打印了正确的数据
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear ----- \(sectionTitle)")
}
(打印的视图将出现---Burton Bindings
)
我想我的问题是由于ViewForSupplementElementOfKind的生命周期,以及何时调用它
我如何在VC加载时获得要显示的节标题,而不必在屏幕上滚动标题才能显示?我看到两种可能的替代方法(如果我正确理解了您的用例,最好先在屏幕上滚动标题) 1) 在视图控制器实例化时(即在加载视图之前)使节标题可用 2) 在出现之前重建分区布局(当您的标题可用时)-这一个很重
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear ----- \(sectionTitle)")
// as it is available here force rebuild sections
self.collectionView.collectionViewLayout.invalidateLayout()
}
这里的问题是在ViewForSupplementalElementOfKind出现之前调用ViewForSupplementalElementOfKind。在ViewWillDisplay中,我正在重新加载集合视图。要正确显示节头标题,我所要做的就是在
之后在viewwillbeen中更新它
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// ---
allCollectionView.reloadItems(at: allCollectionView.indexPathsForVisibleItems)
// Access the SectionHeader and update the title now.
let headerView = allCollectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader)[0] as! SectionHeader
headerView.sectionHeaderLabel.text = "Select \(sectionTitle)"
}
在视图中没有为种类的SupplementalElement设置文本
这里的技巧是在重新加载collectionView后更新视图中的headerView部分HeaderLabel文本