【问题标题】:Change color of text in tableview when pressed按下时更改表格视图中文本的颜色
【发布时间】:2014-06-29 00:32:58
【问题描述】:

好吧,基本上我有一个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 在按下时的工作方式。

【问题讨论】:

    标签: ios objective-c uitableview colors


    【解决方案1】:

    正确的做法是将 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 方法。

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

    【讨论】:

      猜你喜欢
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 2015-06-03
      • 2012-08-17
      • 1970-01-01
      • 2021-10-04
      相关资源
      最近更新 更多