简体   繁体   English

UITableView单元格选择

[英]UITableView cell selection

I've got a UILabel with a background color in a cell. 我在单元格中有一个带有背景颜色的UILabel。 When I select this cell, the cell changes the color (which it should) but it also changes the background of the label. 当我选择此单元格时,该单元格会更改颜色(应更改的颜色),但也会更改标签的背景。 I want the preserve the background color on the UILabel. 我想要在UILabel上保留背景颜色。 When I use an image with just a random color in it it is preserved, but isn't there any better way? 当我使用仅具有随机颜色的图像时,会保留它,但是没有更好的方法吗?

Thanks in advance 提前致谢

Code: 码:

    _label = [UILabel new];
    _label.translatesAutoresizingMaskIntoConstraints = NO;
    _label.font = [UIFont systemFontOfSize:10.f];
    _label.backgroundColor = HEXCOLOR(0xFFE5E5E5); //Macro just a UIColor

But I use this way to add a different selection color (could have something to do with it) 但是我使用这种方式添加了不同的选择颜色(可能与此有关)

    UIView *selectionColor = [[UIView alloc] init];
    selectionColor.backgroundColor = HEXCOLOR(0XFFF1F1F1);
    self.selectedBackgroundView = selectionColor;
    self.contentView.backgroundColor = [UIColor whiteColor];

Nothing really more to it. 仅此而已。 Just a simple label added with autolayout to fill with a padding of 5. 只是添加了自动布局的简单标签即可填充5的填充。

Solution: Create a subclass of UILabel and just not call super 解决方案:创建UILabel的子类,只是不调用super

- (instancetype) initWithColor:(UIColor *)color
{
    self = [super init];
    if (self) {
         [super setBackgroundColor:color];
    }
    return self;
}

- (void) setBackgroundColor:(UIColor *)backgroundColor
{
    //do nothing here!   
}

The default behavior of UITableView is that when a cell is selected the background color of all the cell's subviews is temporarily removed. UITableView的默认行为是,当选择一个单元格时,将暂时删除该单元格的所有子视图的背景色。

We usually handled this issue by subclassing UILabel , overwrite setBackgroundColor: and simply do not call [super setBackgroundColor:] after we've set our own color. 通常,我们通过子类化UILabel来解决此问题,覆盖setBackgroundColor:并在设置自己的颜色后根本不调用[super setBackgroundColor:]

@interface MyLabel : UILabel

@property(nonatomic) BOOL backgroundColorLocked;

@end


@implementation MyLabel

-(void) setBackgroundColor:(UIColor*)backgroundColor {
    if (_backgroundColorLocked) {
        return;
    }

    super.backgroundColor = backgroundColor;
}

@end

Usage: 用法:

MyLabel* label = …;
label.backgroundColor = UIColor.redColor;
label.backgroundColorLocked = YES;

As long as backgroundColorLocked is YES no-one, not even UITableView(Cell) , can change the label's background color. 只要backgroundColorLockedYES ,就不能更改标签的背景色,甚至UITableView(Cell)也不可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM