【问题标题】:Chang color of item in tableview when pressed按下时更改表格视图中项目的颜色
【发布时间】:2014-06-26 22:20:44
【问题描述】:

我有一个表格视图,表格视图中充满了来自 .plist 的项目。

然后我使用此方法在按下某物时添加功能:

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

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

以此类推

我已经在 IB / Storyboard 中设置了字体颜色,但是我想在按下文本时更改它的颜色。所以基本上我希望它在按下时表现得像一个 UIButton。

当然,当按下一个单元格时,并不是所有的文本都应该改变,只有当前单元格中被按下的文本的颜色会改变。

【问题讨论】:

  • 当你按下单元格时只改变文本或改变单元格的背景颜色
  • 检查我的答案是否已优化

标签: ios uitableview colors tableview


【解决方案1】:

您可以更改所选单元格中的所有内容

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

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.font=[UIFont fontWithName:@"Arial"];
 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:@"Arial"];
 cell.contentView.backgroundColor = //default color;
}

【讨论】:

  • 按下后是否可以恢复原来的颜色?所以基本上当按下它会改变颜色,当它释放时它会恢复到原来的颜色
  • 您应该在 deSelectRowAtIndexPath @user243318 中使用具有默认颜色的相同代码
【解决方案2】:
UIView *selectedBackgroundView = [[UIView alloc] init];
selectedBackgroundView.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = selectedBackgroundView;

【讨论】:

    【解决方案3】:
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
     UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    
     if (indexPath.row == 0) 
     { 
       cell.labelText.color = [UIColor redColor];
     }
    
     if (indexPath.row == 1) 
     { 
     cell.labelText.color = [UIColor greenColor];
     }
    }
    

    【讨论】:

      【解决方案4】:

      一个选项(我假设你有一个 UITableViewCell 子类 MyTableViewCell,根据需要进行调整):

      -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
          if (indexPath.row == 0) { //do something
      }
      
      if (indexPath.row == 1) { //do something
      }
      
      MyTableViewCell *cell = (MyTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
      // Adjust your cell contents as needed
      

      还添加取消选择委托方法以恢复更改:

          -(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
       MyTableViewCell *cell = (MyTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
          // Adjust your cell contents back to normal     
      

      另一种选择是覆盖 UITableViewCell 子类中的 setSelected:animated: 和 setHighlighted:animated 并对那里的单元格元素进行适当的更改。

      【讨论】:

        猜你喜欢
        • 2014-06-29
        • 2017-11-23
        • 1970-01-01
        • 2014-06-19
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 2022-07-19
        • 2014-08-27
        相关资源
        最近更新 更多