UITableViewCell在点击时编辑单元格内容

时间:2015-04-25 14:07:33

标签: ios objective-c uitableview

我有一个关于UITAbleViewCell的问题。

我已经实施了UITableViewDelegate方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

    cell.backgroundColor = [UIColor redColor];
    cell.textLabel.textColor = [UIColor redColor];
    cell.textLabel.text = @"Title";
}

点击所需的单元格后,没有任何反应......

为什么它不像我预期的那样工作?另外,我该怎么做才能使它发挥作用?

2 个答案:

答案 0 :(得分:2)

您必须为单元格状态创建一些基本模型,例如:

@property NSString *modelState = @"red"; // this is fast hint, but it can be a enum with states.

点击后,所有单元格都会有一个标题。

......其他控制器代码......

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        UITableViewCell *cell = [self.restaurantTable  dequeueReusableCellWithIdentifier:@"cell_ID"];
// cell customization method        
       [self customizeCell:cell accordingToStateStr:modelState];

        return cell;
    }

......其他控制器代码......

  - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];

    // Set other state for cell
       self.modelState = @"red";

    [tableView reloadData];
    }

- (void)customizeCell:(UITableViewCell*)cell accordingToStateStr:(NSString *)str {
   if ([str isEqualToString:@"red"]) {
  cell.backgroundColor = [UIColor redColor];
    cell.textLabel.textColor = [UIColor redColor];
    cell.textLabel.text = @"Title";
   } else if(...) {
    //Other options..
   }
}

[tableView reloadData]; - 将再次触发“cellForRow”方法,您的表格将根据新模型重新绘制。

您可以使用单元状态emuns而不是NSString对象(这只是您的脚手架)。

答案 1 :(得分:1)

试试这个:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // config the selected cell
    ....
}

您应该直接向UITableView询问单元格,而不是询问其代理人(代码中为self)。因为它的代表可能会出列或创建一个新的细胞,而不是给你单元格。