我想让UITableViewCell文本颜色在选中时更改,但仅限于此。我想禁用单元格中的背景突出显示。我看到了解决方案:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
但这也会禁用文本颜色更改。我想以简单的方式实现这种行为吗?
在你的cellForRowAtIndexPath
,做:
步骤1.将您的选择样式设置为默认值。
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
步骤2.将空视图设置为背景视图
UIView *view = [UIView new] ;
[view setBackgroundColor:[UIColor clearColor]];
[cell setSelectedBackgroundView:view];
第3步。设置所需的文字颜色
[[cell textLabel] setTextColor:[UIColor orangeColor]];
[[cell textLabel] setHighlightedTextColor:[UIColor blackColor]];
希望这可以帮助。
在您的自定义tableview单元格类中,重写setSelected
方法并根据选择状态更新文本颜色。
例如:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if (selected) {
[self.textLabel setTextColor:[UIColor orangeColor]];
} else {
[self.textLabel setTextColor:[UIColor blackColor]];
}
}
在cellForRowAtIndexPath
中禁用默认单元格选择
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
您应该尝试使用-tableView:didSelectRowAtIndexPath:
然后你应该能够在单元格中定位文本(取决于它是如何设置的,以及标签是否是单元格的属性)
Cell.textLabel.textColor=[UIColor graycColor];
Cell.textLabel.backgroundColor = [UIColor blackColor];
试试你的cellForRowAtIndexPath
Swift 4 / iOS 11.2 / Xcode 9.2:
覆盖setSelected就是答案。
如果您希望默认行为加上其他一些更改,请单独保留selectionStyle,或将其设置为.default:
selectionStyle = .default
如果您想要所有自定义行为,请将其设置为.none:
selectionStyle = .none
无论哪种方式 - 即使您将其设置为.none,您的被覆盖的setSelected仍将被调用。例如:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
textLabel.textColor = orange
} else {
textLabel.textColor = black
}
}