iOS

您所在的位置:网站首页 contentsize iOS

iOS

2024-03-12 07:39| 来源: 网络整理| 查看: 265

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

1、添加监听

需要在控件创建时添加

[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil]; 2、监听方法 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)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 *)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); }]; } } }


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3