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,113評論 8 183
  • 五月的晴天,在我看來是最好最好的了,不冷不熱,蚊蟲此時也不甚惱人的。陽光就是常像現在這樣,直爽爽的撲在人身上,...
    安山遠閱讀 267評論 1 1
  • 怎麼抓重點,人的習慣常常是在抓自己的重點 忽略了別人的重點。 自己的體會是 每個人雖然都活在這共同的世界 但其實每...
    腦子長在手上閱讀 176評論 0 0
  • 今天繼續學習選擇結構,但還是要重點復習一下的是運算符的優先級。 1、!(非)算術運算符,關系運算符,&&和||,賦...
    重耳兄閱讀 350評論 0 2
  • 生病總是一件令人難受的事,但不一定是一件壞事。不生病,怎么體會秦瓊賣馬,英雄末路的凄涼;不生病,如何知道肝腸寸斷,...
    chi樂22閱讀 435評論 0 1