用KVO来监听 UICollectionView及 contentSize、contentOffset和contentInset的图解辨别
// 懒加载 UICollectionView
- (UICollectionView *)myCollectionView {
if (!_myCollectionView) {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
CGFloat width = GET_SCREEN_WIDTH-(isPad?82:0);
CGFloat height = GET_SCREEN_HEIGHT-(64+(isPad?20:0));
self.myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, width, height) collectionViewLayout:flowLayout];
_myCollectionView.backgroundColor = [UIColor clearColor];
_myCollectionView.scrollEnabled = false;
_myCollectionView.delegate = self;
_myCollectionView.dataSource = self;
// _myCollectionView.contentInset = UIEdgeInsetsMake(64, 0, 20, 0);
// _myCollectionView.userInteractionEnabled = NO;
[self registerMyCell];
[self p_registerObserve];
}
return _myCollectionView;
}
#pragma mark - KVO
- (void)p_registerObserve {
if (_myCollectionView) {
[_myCollectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:kCollectionViewContentSizeContext];
}
}
- (void)p_deregisterObserve {
// 这里不使用点语法触发懒加载,因为可能在这里才触发懒加载创建collectionView,此时还没有添加观察者
// 如果这时移除观察者很可能会造成崩溃
if (_myCollectionView) {
[_myCollectionView removeObserver:self forKeyPath:@"contentSize" context:kCollectionViewContentSizeContext];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (context == kCollectionViewContentSizeContext) {
CGSize contentSize = [change[NSKeyValueChangeNewKey] CGSizeValue];
CGFloat width = GET_SCREEN_WIDTH-(isPad?82:0);
self.myCollectionView.frame = CGRectMake(0, 0, width, contentSize.height);
self.baseTableView.tableFooterView = self.myCollectionView;
}
}