如何在选中时设置表格视图单元格边框和颜色

时间:2014-07-24 09:32:31

标签: objective-c uitableview

我有以下代码设置在自定义表格视图单元格周围设置一个红色边框,选中它时中间是白色。

- (void)awakeFromNib
{
 self.nameLabel.highlightedTextColor = [UIColor whiteColor];

 // Set selected background view
 UIView *backgroundView = [[UIView alloc]initWithFrame:self.bounds];
 backgroundView.layer.borderColor = [[UIColor redColor] CGColor];
 backgroundView.layer.borderWidth = 10.0f;
 self.selectedBackgroundView = backgroundView;

 // Set the content view
 CGRect frame  = CGRectMake(self.bounds.origin.x+5, self.bounds.origin.y+5, self.bounds.size.width-10, self.bounds.size.height-10);
 UIImageView *myImageView = [[UIImageView alloc] initWithFrame:frame];
 [self addSubview:myImageView];
 self.imageView.contentMode = UIViewContentModeScaleAspectFill ;
 self.imageView.clipsToBounds = YES;
 [self.contentView addSubview:self.imageView]; 
}

我想要反过来说:你如何创建一个红色并带有白色边框/填充的单元格?

3 个答案:

答案 0 :(得分:1)

您可以使用

[cell.contentView.layer setBorderColor:[UIColor redColor].CGColor]; 
[cell.contentView.layer setBorderWidth:2.0f]; 

希望这会对你有所帮助

答案 1 :(得分:1)

在自定义单元格中尝试此方法- (void)setSelected:(BOOL)selected animated:(BOOL)animated使用此方法来更改所选状态和取消选择状态,例如

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
 {
   [super setSelected:selected animated:animated];
   if(selected)
   {
    self.contentView.layer.cornerRadius = 10.0f;
    self.contentView.layer.borderWidth  = 5.0f;
    self.contentView.layer.masksToBounds = YES;
    self.contentView.backgroundColor = [UIColor redColor];
    self.contentView.layer.borderColor  = [UIColor whiteColor].CGColor;

  }
  else
  {
    self.contentView.layer.cornerRadius = 10.0f;
    self.contentView.layer.borderWidth  = 5.0f;
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.borderColor  = [UIColor redColor].CGColor;
  }

  // Configure the view for the selected state
}

并在创建单元格时为单元格设置customCell.selectionStyle = UITableViewCellSelectionStyleNone;

答案 2 :(得分:0)

为什么不尝试做相反的事情,比如这个

 UIView *backgroundView = [[UIView alloc]initWithFrame:self.bounds];
 backgroundView.layer.borderColor = [[UIColor whiteColor] CGColor];
 backgroundView.layer.borderWidth = 10.0f;
 self.selectedBackgroundView = backgroundView;

 // Set the content view
 CGRect frame  = CGRectMake(self.bounds.origin.x+5, self.bounds.origin.y+5, self.bounds.size.width-10, self.bounds.size.height-10);
 UIImageView *myImageView = [[UIImageView alloc] initWithFrame:frame];
myImageView.backgroundcolor=[UIColor redColor];
 [self addSubview:myImageView];
 self.imageView.contentMode = UIViewContentModeScaleAspectFill ;
 self.imageView.clipsToBounds = YES;
 [self.contentView addSubview:self.imageView];