仅更改自定义UITableViewCell所选背景颜色的一部分

时间:2013-08-08 14:20:22

标签: uitableview

我有一个自定义单元格,我控制它被选中的颜色,即下面的示例代码:

UIView *selectedBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 600, 600)];
[selectedBackground setBackgroundColor:[UIColor selectedCellColor]];
self.selectedBackgroundView = selectedBackground;

这是有效的,但是我只想在选择时让部分单元改变颜色。我的自定义单元格被分解为许多不同的子视图,我将它划分出来,我可以在哪里定义我想要更改颜色的特定视图。

如何控制selectedBackgroundView或使用其他方法让背景颜色更改包含单元格中的单个子视图?

1 个答案:

答案 0 :(得分:1)

雅你是通过继承UITableView单元格的方式 听到的是示例代码,您可以找到问题的答案:)

 //in subclassed cell class

 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  {
   self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
   if (self) {
    // Initialization code

    self.frame = CGRectMake(0, 0, 334, 250);
    UILabel *aLabel1= [[UILabel alloc]init];
    UILabel *aLabel2 = [[UILabel alloc]init];


    self.label1 = aLabel1;
    self.label2 = aLabel2;


    self.label1.text = @"Happy";
    self.label2.text = @"coding";




    UIImageView *bg1 = [[UIImageView alloc]init];
    bg1.tag = 100;

    UIImageView *bg2 = [[UIImageView alloc]init];
    bg2.tag = 200;

    [self addSubview:bg1]; // you must add your background views first
    [self addSubview:bg2];

    [self addSubview:label1];//then other views
    [self addSubview:label2];

    [aLabel1 release];
    [aLabel2 release];

    [bg1 release];
    [bg2 release];

}
return self;

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
   // Configure the view for the selected state

    // hear only you can manage your background views, simply i am adding 2 imageviews by setting different colors 
[super setSelected:selected animated:animated];
self.backgroundColor = [UIColor greenColor];
if(selected)
{
    self.label1.backgroundColor = [UIColor redColor];
    self.label2.backgroundColor = [UIColor brownColor];
    UIImageView *bg1 = (UIImageView *)[self viewWithTag:100];
    bg1.frame = CGRectMake(0, 0,334/2, 250);
    bg1.backgroundColor = [UIColor yellowColor];


}
else
{
    self.label1.backgroundColor = [UIColor brownColor];
    self.label2.backgroundColor = [UIColor redColor];
    UIImageView *bg2 =(UIImageView *) [self viewWithTag:200];
    bg2.frame =  CGRectMake(35, 0, 334/2, 250);
    bg2.backgroundColor = [UIColor lightGrayColor];
 }

}

   -(void)layoutSubviews
  {

    //i am setting the frame for each views that i hav added
   [super layoutSubviews];
   self.label1.frame = CGRectMake(10, 10, 60, 35);
    self.label2.frame = CGRectMake(65, 10, 60, 35);

 }


希望能帮到你:) 注意:我正在使用“没有ARC”