我正在尝试为待办事项列表类型的应用程序制作详细屏幕。下面是详细当前屏幕上的样子:自动调整UICollectionView标题
这是一个UICollectionViewController
,一个头。标题包含2个UILabel
对象和一个UITextView
对象。这些对象的布局由垂直UIStackView
进行管理。 A UIView
用于设置白色背景。
我在运行时定义此UICollectionReusableView
的高度时遇到了一些困难。任何建议表示赞赏。
我正在尝试为待办事项列表类型的应用程序制作详细屏幕。下面是详细当前屏幕上的样子:自动调整UICollectionView标题
这是一个UICollectionViewController
,一个头。标题包含2个UILabel
对象和一个UITextView
对象。这些对象的布局由垂直UIStackView
进行管理。 A UIView
用于设置白色背景。
我在运行时定义此UICollectionReusableView
的高度时遇到了一些困难。任何建议表示赞赏。
下面是如何处理自定义UICollectionViewReusableView与自动布局没有XIB文件。
referenceSizeForHeaderInSection
委托方法。setNeedsLayout
和layoutIfNeeded
注意:我不是这个解决方案的大风扇,因为它每次添加自定义视图到的CollectionView的上海华,执行计算。虽然我没有注意到任何性能问题。
小心#2:我会将其视为临时解决方案,并在发布后迁移到自我尺寸补充视图。
我使用PureLayout进行自动布局。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let header = CustomHeaderView()
header.isHidden = true;
self.view.addSubview(header)
header.autoPinEdge(toSuperviewEdge: .leading)
header.autoPinEdge(toSuperviewEdge: .trailing)
header.autoPin(toTopLayoutGuideOf: self, withInset: 0)
header.setupHeader(withData: self.data)
header.setNeedsLayout()
header.layoutIfNeeded()
header.removeFromSuperview()
return header.frame.size
}
这是一个黑客,但似乎工作。
// showhere to keep a reference
UICollectionReusableView * _cachedHeaderView;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
if(!_cachedHeaderView){
// dequeue the cell from storyboard
_cachedHeaderView = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"header_cell"] forIndexPath:indexPath];
// set captions/images on the header etc...
// tell the collectionview to redraw this section
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
}
return _cachedHeaderView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
// once there is a reference ot the view, use it to figure out the height
if(_cachedHeaderView){
return [_cachedHeaderView systemLayoutSizeFittingSize:collectionView.bounds.size withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityDefaultLow];
}
// a placeholder value just to get the dequeueReusableCellWithReuseIdentifier to work
return CGSizeMake(collectionView.bounds.size.width, 100);
}
看起来,Self-Sizing单元格大多满足非常基本的情况,仍然需要使用这些类型的页眉或页脚。 –
http://stackoverflow.com/a/33696385/6064629也许它会帮助你。 – Himanshu
谢谢@himanshu。我仍然希望有比这更好的答案,因为该解决方案基本上实例化了一个额外的'UICollectionReusableView'副本,并在之后立即抛出它。 –
@KelvinLau你设法弄清楚什么?我不是所提供解决方案的忠实粉丝,因为它需要XIB文件。 – Michael