按下时更改tableview中文本的颜色

时间:2014-05-11 17:17:23

标签: ios objective-c uitableview colors

好吧基本上我有一个tableView填充在“.plist”中的项目。

tableView然后从此代码中获取其功能:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) { 
//do something
}

if (indexPath.row == 1) { 
//do something
}

但是我希望tableView中的项目或文字在按下时改变颜色,当它被释放时它应该恢复原来的颜色。

然后我添加了此代码来更改背景颜色,因为我找不到任何更改文本的内容:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.font=[UIFont fontWithName:@"Helvetica" size:22.0];
    cell.contentView.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];

但问题是它仍然保留了这种背景色。

然后我尝试创建一个这样的取消选择方法:

-(void)tableView:(UITableView *)tableView deSelectRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.font=[UIFont fontWithName:@"Helvetica" size:22.0];
cell.contentView.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:1.0 alpha:2.0];

}

然而,这不会再次改变颜色。

所以基本上我要么想要在按下时改变背景颜色或文本颜色,然后在它被释放时改回原来的颜色。非常类似UIButton按下时的工作原理。

1 个答案:

答案 0 :(得分:0)

正确的方法是将selectedBackgroundView和backgroundView设置为单元格。

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
  if(!cell){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
    UIView * selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    selectedBackgroundView.backgrounColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
    cell.selectedBackgroundView = selectedBackgroundView
   }

  return cell;
}

这样,您无需在选择完成后设置背景颜色,并在取消选择时更改颜色。

如果您想根据选择更改文本属性,子类UITableViewCell并覆盖setSelected:animated method。

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
 [super setSelected:selected animated:animated];
 self.textLabel.titleColor.textColor = selected ? selectedColor : notSelectedColor;
}
相关问题