前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS TableViewCell中的KVO的使用

iOS TableViewCell中的KVO的使用

作者头像
赵哥窟
发布2020-02-13 15:10:57
1.1K0
发布2020-02-13 15:10:57
举报
文章被收录于专栏:日常技术分享

比如我们在写消息列表的时候,未读消息一般都有个红点,点击一下红点消失。这个功能通常的做法就是Model中标识消息已读。然后在Reload TableView或者Cell。 但是还有个方法可以实现那个就是KVO

代码语言:javascript
复制
#import "MessageCell.h"

@implementation MessageCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code

    self.bradgeView.layer.masksToBounds = YES;
    self.bradgeView.layer.cornerRadius = 5;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setMsgModel:(MessageModel *)msgModel{
    _msgModel = msgModel;
    self.msgLbl.text = msgModel.msgTitle;
    if ([msgModel.isRead integerValue] == 1) {
        self.bradgeView.hidden = YES;
    }else{
         self.bradgeView.hidden = NO;
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"isRead"] && [object isKindOfClass:[MessageModel class]]) {
        
        if ([self.msgModel.isRead integerValue] == 1) {
            _bradgeView.hidden = YES;
        }
    }
}
注册KVO监听
代码语言:javascript
复制
- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (_msgDataArr.count > indexPath.row) {
         MessageModel *msgModel = _msgDataArr[indexPath.row];
        [msgModel addObserver:cell forKeyPath:@"isRead" options:NSKeyValueObservingOptionNew context:nil];
    }
}
移除KVO监听
代码语言:javascript
复制
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
     if (_msgDataArr.count > indexPath.row) {
          MessageModel *msgModel = _msgDataArr[indexPath.row];
         [msgModel removeObserver:cell forKeyPath:@"isRead"];
     }
 }

使用KVO来监听isRead属性,当点击Cell的时候处理

代码语言:javascript
复制
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageModel *msgModel = _msgDataArr[indexPath.row];
    if ([msgModel.isRead integerValue] != 1) {
        msgModel.isRead = @"1";
    }
    
}

Demo 下载

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 注册KVO监听
  • 移除KVO监听
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档