开发者社区> 问答> 正文

UITableViewCell 的重用问题。

我每个 cell 里面都有一个 button,我为 button 设置了一个点击响应动作 btn_tapped
在 btn_tapped 里面我把 sender 转换成 button 对象,并操作它:比如设置为隐藏。但是发现跟它共用同一个内存 button 也隐藏起来了。
有没有什么方法可以拿到 button 并且设置属性又不冲突的?

展开
收起
a123456678 2016-07-27 16:26:55 1833 0
1 条回答
写回答
取消 提交回答
  • 以咱们这个问题为例,比如,我们的tableView数据源是timelineArray,保存着一个timeline列表。假如Button是“赞”这个按钮的话,我们之所以要展示这个“赞”按钮,是因为当前这条timeline中的isLiked(是否被赞)属性为NO.所以这样写:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {     
        BtnTableViewCell *cell = (BtnTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"BtnTableViewCell"];
    
        NSDictionary* timeline = [self.timelines objectAtIndex:indexPath.row];
        BOOL isLiked = [[timeline objectForKey:@"isLiked"] boolValue];
        //tableViewCell的样式是和数据源有关的,所以我们是根据数据源来确定样式。为了阅读方便写成下面这样,其实是可以写成一行:cell.likeButton.hidden = !isLiked;
        if (isLiked) {           
            cell.likeButton.hidden = YES;
        }else{            
            cell.likeButton.hidden = NO;
        }
        //我们最好再给button再加一个tag,方便标识之后点击的时候确定点击了哪条timeline
        cell.likeButton.tag = indexPath.row;
        return cell;
    }
    因为在滑动tableview时,就是通过cellForRowAtIndexPath来复用cell的,所以数据源的改变,cell的样式也会改变。同时,我们进行任何操作时,本来就会更新数据源的最新状态,这是最正确的做法。
    
    - (void)btn_tapped:(id)sender
    {
        if(![sender isKindOfClass:[UIButton class]){
            return;
        }
        UIButton *btn = (UIButton*)sender;
        //通过tag来获取到timeline的index
        NSInteger row = btn.tag;
    
        //【1】立即隐藏该按钮;
        btn.hidden = YES;        
        //【2】标记数据源,例如保存这条消息已经被赞过了,方便接下来复用cell时识别
        NSMutableDictionary *timeline = [self.timelines objectAtIndex:row];
        [timeline setObject:[[NSNumber alloc] initWithBool:YES] forKey:@"isLiked"];
    }
    2019-07-17 20:00:49
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载