最近發現,以前寫的單個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復用不會導致樣式的錯亂。