有時候布局會遇到TableView和CollectionView組合布局,比如上部分是輪播,中間部分是列表顯示,最下面是瀑布流,滑動Header還需要懸浮功能,簡單的tableView或者collectionView已經(jīng)無法滿足需求了,這樣我們可以采用UITableView鑲嵌UICollectionView來實現(xiàn)這一需求。
最外面一層使用tableView,在tableView的一個cell鑲嵌collectionView,其實最大的問題就是要知道collectionView的高度,這里我們使用kvo來監(jiān)聽它的contentSize值從而獲取它的高度。
下面是具體做法:
1、設置鑲嵌collectionView的cell的高度為自動,我們使用自動布局來撐滿整個cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return indexPath.section == 4 ? UITableViewAutomaticDimension : (indexPath.section == 1 ? 140 : 170);
}
2、cell中先設置collectionView的監(jiān)聽
[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
3、增加collectionView進行自動布局,這里的高度隨便設置一個,后面我們監(jiān)聽到contentSize會更新這個值
[self.contentView addSubview:self.collectionView];
[_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.contentView);
make.height.equalTo(600);
}];
4、監(jiān)聽contentSize更新高度
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey,id> *)change
context:(void *)context{
if ([keyPath isEqualToString:@"contentSize"])
{
CGFloat height = self.collectionView.contentSize.height;
[self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
make.height.equalTo(@(height));
}];
}
}
5、更新數(shù)據(jù)源刷新collectionView
[self.collectionView reloadData];
[self.collectionView layoutIfNeeded];
到此大功告成!