Ios 以编程方式设置集合视图标题的动态高度的最佳方法?
我有一个视图Ios 以编程方式设置集合视图标题的动态高度的最佳方法?,ios,swift,uicollectionview,height,uicollectionreusableview,Ios,Swift,Uicollectionview,Height,Uicollectionreusableview,我有一个视图HeaderView,它是UICollectionReusableView的子类,是一个UIStackView用标签排列一些子视图。这些标签的数量和文本取决于向服务请求的信息 该视图通过以下方式注册到集合视图: collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderView
HeaderView
,它是UICollectionReusableView
的子类,是一个UIStackView
用标签排列一些子视图。这些标签的数量和文本取决于向服务请求的信息
该视图通过以下方式注册到集合视图
:
collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderView.reuseIdentifier)
然后,我实现了collectionView(u:viewforsupplementalelementofkind:at:)
方法,如下所示:
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
if let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: HeaderView.reuseIdentifier,
for: indexPath) as? HeaderView {
// Provide the headerView with the texts it needs to show
return headerView
}
fatalError("no view")
default:
fatalError("no view")
}
}
并且还实现了collectionView(uu:layout:referenceSizeForHeaderInstruction:)
方法
我的问题是首先调用collectionView(uquot:layout:referenceSizeForHeaderInstitution:)
,此时headerView尚未实例化,因此我无法获取其实际高度。我也不能提供一个固定的高度,因为正如我所说的,这种headerView的高度将取决于我从服务中获得的信息,并且它将是可变的
我没有使用故事板或xib文件,而是创建所有视图并在代码中设置布局
我还应该补充一点,实际上我需要这个
HeaderView
作为我的集合视图中一个部分的标题,所以我可能不需要将它出列并重用它?在这种情况下,我建议计算堆栈视图的高度,并使用collectionView(uuu2;:布局:referenceSizeForHeaderInstruction:)
例如,我只需要在viewdiload
中实例化它,并将其存储在属性中,这样您就可以为collectionView(uu2;:layout:referenceSizeForHeaderInstitution:)
做好准备。@trungduc我考虑过“手动”计算标题视图的高度,但我认为这听起来不太“优雅”,可能有点复杂。。。不可能以某种方式依赖自动布局吗?@Ladislav,我认为它不起作用。。。因为我不知道调用其init
时,HeaderView
应该具有的frame
是否使用自动布局?