禁用背景颜色更改,但在UITableViewCell突出显示时启用文本颜色更改

问题描述 投票:1回答:5

我想让UITableViewCell文本颜色在选中时更改,但仅限于此。我想禁用单元格中的背景突出显示。我看到了解决方案:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

但这也会禁用文本颜色更改。我想以简单的方式实现这种行为吗?

ios objective-c uitableview
5个回答
5
投票

在你的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]];

希望这可以帮助。


1
投票

在您的自定义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];

0
投票

您应该尝试使用-tableView:didSelectRowAtIndexPath:

然后你应该能够在单元格中定位文本(取决于它是如何设置的,以及标签是否是单元格的属性)


0
投票
Cell.textLabel.textColor=[UIColor graycColor];
Cell.textLabel.backgroundColor = [UIColor blackColor];

试试你的cellForRowAtIndexPath


0
投票

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.