1

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

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

这可行,但是我只想让部分单元格在选择时更改颜色。我的自定义单元格被分解为许多不同的子视图,我将其划分为可以定义我想要更改颜色的特定视图的位置。

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

4

1 回答 1

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”

于 2013-08-09T04:57:58.363 回答