iOS 在Tableview中监听cell中属性值改变,UI也随之改变

6 篇文章 0 订阅

前言:要实现如题的功能,有好几种方法
1、 NSNotification通知
2、Delegate委托
3、修改当前操作的cell,修改该model中值,然后替换数组的中,然后再刷新当前的cell
4、kvo实现,就是我们待会要说的。
需要注意的是:
我们在cell中添加了多少监听,那么也就要移除多少个,在返回上级页面时,还需要将可见cell中的监听移除

参考链接地址这里写链接内容

一、我们在cell中的监听代码

//1、在配置cell显示的地方,添加监听
[model addObserver:self forKeyPath:@"isStore" options:NSKeyValueObservingOptionNew context:nil];

//监听到属性值改变,执行的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {

    if ([keyPath isEqualToString:@"isStore"]) {
        _collectBtn.hidden = NO;
        if ([StringUtil isBlank:currentModel.isStore]) {
            [_collectBtn setImage:[UIImage imageNamed:@"collectBgNo"] forState:0];
        }else{
            [_collectBtn setImage:[UIImage imageNamed:@"collectBgYes"] forState:0];
        }
    }
}

//3、移除监听,currentModel记录当前的model
- (void)dealloc {
    [currentModel removeObserver:self forKeyPath:@"isStore"];
}

二、在VC中添加相关cell的监听

//1、cell即将出现时,添加相关cell监听
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NewTrainingDetailsModel *model = dataArray[indexPath.row];
    [model addObserver:cell forKeyPath:@"isStore" options:NSKeyValueObservingOptionNew context:nil];
}
//2、cell即将消失时,移除相关cell监听
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NewTrainingDetailsModel *model = dataArray[indexPath.row];
    [model removeObserver:cell forKeyPath:@"isStore"];
}

//3、移除监听
- (void)dealloc {
    NSArray *cells = [_myTableView visibleCells];
    for (int i = 0; i < cells.count; i++) {
        NewTrainingDetailsCell *cell = (NewTrainingDetailsCell *)cells[i];
        NSIndexPath *indexPath = [_myTableView indexPathForCell:cell];
        NewTrainingModel *model = dataArray[indexPath.row];
        [model removeObserver:cell forKeyPath:@"isStore"];
    }

三、点击按钮,触发相关属性值改变的代码

//点击按钮,操作成功后,修改当前操作model的值,此时就会触发observeValueForKeyPath方法,随时UI改变
//收藏成功的
 NewTrainingDetailsModel *model = dataArray[index];
 model.isStore = @"yes";
 //取消收藏成功的
 //model.isStore = @"";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值