ios KVO设置TableView和Collectionvie

2018-06-21  本文已影响87人  ClementGu

需求

tableView或collectionview为界面一个控件,并且在无数据的时候不显示,在有数据的时候按照数据多少显示高度和内容相等。

思路

利用KVO原理。因为tableView和Collectionview都继承于UIScrollview,所以根据其contentSize来实时检测其contentsize大小并且根据其内容来动态设置其高度。

代码

//声明tableview
@property (nonatomic,strong) UITableView *showTBV;

//初始化
_showTBV = [UITableView new];
    _showTBV.delegate = self;
    _showTBV.dataSource = self;
    [_showTBV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    _showTBV.separatorStyle = UITableViewCellSeparatorStyleNone;
    /** 添加监听 */
    [_showTBV addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    [self addSubview:_showTBV];

//约束 这边table再自定义view中
-(void)layoutSubviews
{
    [super layoutSubviews];
    [_showTBV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];

}

//移除监听
-(void)dealloc
{
    [_showTBV removeObserver:self forKeyPath:@"contentSize"];
}

/** 监听自适应高度 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGFloat ht = _showTBV.contentSize.height;
        [_showTBV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(ht);
        }];
    }
}

Collectionview 同理

上一篇下一篇

猜你喜欢

热点阅读