时候需要加载完 UITableView、UICollectionView内容后,确定高度宽度来改变它的Frame,这时候可以巧妙地使用KVO添加对其 contentSize监听进行处理,以 UICollectionView 为例逻辑需要在 UICollectionView 加载完后,拿到内容大小进行处理其Frame,在添加 UICollectionViewview 初始化方法中,添加监听即可
1、添加监听监听方法处理移除监听
2、添加监听监听方法处理-移除监听;
3、添加监听-监听方法处理-移除监听;

1、添加监听

需要控件创建时添加

[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

2、监听方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id&gt; *)change context:(void *)context
{
    if(object == self.collectionView){
        if ([keyPath isEqualToString:@"contentSize"]) {
            if(_collectionView.contentSize.height == _contentHeight) return;
            _contentHeight = _collectionView.contentSize.height;
            ///对其拿到的高或者宽进行处理
        }
    }
}

3、移除监听

- (void)dealloc
{
    [self.collectionView removeObserver:self forKeyPath:@"contentSize"];
}

4、我的监听添加方法

#pragma mark -- 监听tableView的滚动
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (object == self.marketView.myTableView) {
        CGPoint point = [((NSValue *)[self.marketView.myTableView valueForKey:@"contentOffset"]) CGPointValue];
        NSInteger y = point.y;
        if ( y >= 0 ) {
            if (y >= 25) {
                y = 25;
            }
            [self.headScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_offset(85-y);
            }];
        }
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注