轻敲单元格时,更改表格单元格内UILabel的颜色

时间:2014-07-07 07:18:47

标签: ios objective-c uitableview uilabel

我有一个内置UIImage和UILabel的单元格:

enter image description here

我有这个代码用于设置其内容,非常标准的东西:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *itemCellID = @"menuItem";

    NSString *currentMenuLabel = [self.menuItemStructure objectAtIndex:[indexPath row]];
    NSString *currentMenuIcon = [self.menuItemIcon objectAtIndex:[indexPath row]]; 
    MTNLeftMenuItemCell *cell = [self.tableView dequeueReusableCellWithIdentifier:itemCellID];
    [cell.leftMenuItemLabel setText:currentMenuLabel];
    UIImage *icon = [UIImage imageNamed:currentMenuIcon];
    [cell.leftMenuItemIcon setImage:icon];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

现在我要做的是在点击单元格时更改此UILabel's文本颜色,类似于css中的.cell .label:hover { ... }。回想起来,这似乎相当明显,但UILabel是细胞的子视图让我感到困惑。

我该怎么做?

2 个答案:

答案 0 :(得分:9)

在选择单元格时调用了一个委托didSelectRowAtIndexPath方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
   UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //Get your cell for selected row       
   cell.leftMenuItemLabel.textColor = [UIColor redColor];//Configure whatever color you want
}

答案 1 :(得分:1)

Janak Nirmal的回答只关注选择。如果要永久地使单元格标签颜色,那么您应该使用indexPath或其他方式跟踪单元格。

每次滚动表格视图时,都可能会创建一个新单元格。所以你的颜色不会被设定。

因此,您必须比较所选索引的indexPath并更改新单元格标签的颜色。

·H

@property (retain, nonatomic) NSIndexPath *selectedIndexPath;

的.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *itemCellID = @"menuItem";

    NSString *currentMenuLabel = [self.menuItemStructure objectAtIndex:[indexPath row]];
    NSString *currentMenuIcon = [self.menuItemIcon objectAtIndex:[indexPath row]];
    MTNLeftMenuItemCell *cell = [self.tableView dequeueReusableCellWithIdentifier:itemCellID];
    [cell.leftMenuItemLabel setText:currentMenuLabel];
    UIImage *icon = [UIImage imageNamed:currentMenuIcon];
    [cell.leftMenuItemIcon setImage:icon];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (self.selectedIndexPath && [indexPath compare:self.selectedIndexPath] == NSOrderedSame){

        [self decorateSelectedLabel:cell];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //Get your cell for selected row
    self.selectedIndexPath = indexPath;
    [self decorateSelectedLabel:cell];
}
- (void)decorateSelectedLabel:(MTNLeftMenuItemCell*)selectedCell{
    selectedCell.leftMenuItemLabel.textColor = [UIColor redColor];//Configure whatever color you want
}

如果您在单元格上有多个选择,则使用数组来保留索引。祝你好运