UITableView单元格选择

时间:2014-10-10 13:42:11

标签: ios objective-c uitableview

我在单元格中有一个背景颜色的UILabel。当我选择此单元格时,单元格会更改颜色(它应该),但它也会更改标签的背景。我希望保留UILabel上的背景颜色。当我使用一个只有随机颜色的图像时,它会被保留,但是没有更好的方法吗?

提前致谢

代码:

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

但我用这种方式添加不同的选择颜色(可能与它有关)

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

没有更多的东西。只是添加了autolayout的简单标签,填充了5的填充。

解决方案: 创建UILabel的子类,而不是调用super

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

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

1 个答案:

答案 0 :(得分:1)

UITableView的默认行为是,当选择一个单元格时,会暂时删除所有单元格子视图的背景颜色。

我们通常通过继承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

用法:

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

只要backgroundColorLockedYES,没有人,甚至UITableView(Cell),就可以更改标签的背景颜色。