4

我正在使用viewForSupplementaryElementOfKind在我的收藏视图中生成标题。

header ( SectionHeader) 是 Storyboard 中的一个 Section Header 附件,仅包含 1 个插座。

class SectionHeader: UICollectionReusableView {
    @IBOutlet weak var sectionHeaderlabel: UILabel!
}

这是我的实现viewForSupplementaryElementOfKind

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 Bindings”

sectionTitle在 viewWillAppear 中进行了测试,并打印了正确的数据。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    print("viewWillAppear ----- \(sectionTitle)")
}

(印刷viewWillAppear ----- Burton Bindings

我想我的问题是由于 viewForSupplementaryElementOfKind 的生命周期,以及何时被调用?

如何在 VC 加载时显示部分标题,而不是在屏幕上滚动标题以使其显示?

4

2 回答 2

0

我看到了两种可能的替代方案(如果我首先正确理解了您的用例,则更可取)。

1)sectionTitle在视图控制器实例化时可用(即在加载视图之前)

2)在出现之前重建部分布局(当你的标题可用时) - 这个很重

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    print("viewWillAppear ----- \(sectionTitle)")

    // as it is available here force rebuild sections
   self.collectionView.collectionViewLayout.invalidateLayout() 
}
于 2020-04-24T18:52:08.877 回答
0

这里的问题是 viewForSupplementaryElementOfKind 在 vi​​ewWillAppear 之前被调用。在 viewWillAppear 中,我正在重新加载 Collection View。为了正确显示部分标题标题,我所要做的就是在 viewWillAppear 中更新它,之后.reloadItems

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)"

}

中没有设置文本viewForSupplementaryElementOfKind

这里的技巧是在重新加载 collectionView后更新 viewWillAppear 中的 headerView sectionHeaderLabel 文本。

于 2020-04-27T17:43:19.687 回答