iOS-UITableViewCell选中遇到的坑

最近发现,以前写的单个cell选中,竟然出了问题,是复用时的问题,导致我重新找到了一个较为完美的解决方法。

默认选中
选中其他
实现过程

1 UITableViewCell

@implementation ResourceListCell

-(void)awakeFromNib{
// 选中背景视图
    UIView *selectedBg = [UIView new];
    selectedBg.backgroundColor = [UIColor colorWithRed:242/255.0 green:177/255.0 blue:74/255.0 alpha:1];
    self.selectedBackgroundView = selectedBg;
    
// 正常背景视图
    UIView *normalBg = [UIView new];
    normalBg.backgroundColor = [UIColor whiteColor];
    self.backgroundView = normalBg;
}

// 这里可以进行一些样式或数据展示方面的设置
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
     if (selected) {
        self.textLabel.textColor = [UIColor whiteColor];
     }
    else{
        self.textLabel.textColor = [UIColor colorWithRed:106/255.0 green:106/255.0 blue:106/255.0 alpha:1];
    }
}

@end

2 UITableViewDataSource

// cell 复用时
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ResourceListCell" forIndexPath:indexPath];
// 数据
// 上次选中的
    if (_indexPathNeedsSelect == indexPath) {
        // 自动选中某行,调用[cell setSelected:]
        [tableView selectRowAtIndexPath:indexPath animated:false scrollPosition:UITableViewScrollPositionNone];
    }
    return cell;
}

// 选中cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 切换数据源
    // 选中
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelected:true]; 
    _indexPathNeedsSelect = indexPath;
}

// 取消选中
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelected:false];
}

这样就可以较为完整的实现 单个cell 选中的功能了,cell复用不会导致样式的错乱。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 24,124评论 8 183
  • 五月的晴天,在我看来是最好最好的了,不冷不热,蚊虫此时也不甚恼人的。阳光就是常像现在这样,直爽爽的扑在人身上,...
    安山远阅读 267评论 1 1
  • 怎麼抓重點,人的習慣常常是在抓自己的重點 忽略了別人的重點。 自己的體會是 每個人雖然都活在這共同的世界 但其實每...
    腦子長在手上阅读 176评论 0 0
  • 今天继续学习选择结构,但还是要重点复习一下的是运算符的优先级。 1、!(非)算术运算符,关系运算符,&&和||,赋...
    重耳兄阅读 356评论 0 2
  • 生病总是一件令人难受的事,但不一定是一件坏事。不生病,怎么体会秦琼卖马,英雄末路的凄凉;不生病,如何知道肝肠寸断,...
    chi樂22阅读 440评论 0 1