我正在嘗試爲待辦事項列表類型的應用程序製作詳細屏幕。下面是詳細當前屏幕上的樣子:自動調整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