前言:要实现如题的功能,有好几种方法
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 = @"";