1. 程式人生 > >iOS 在Tableview中監聽cell中屬性值改變,UI也隨之改變

iOS 在Tableview中監聽cell中屬性值改變,UI也隨之改變

前言:要實現如題的功能,有好幾種方法
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 = @"";