【问题标题】:How do I update a label in a UITableViewCell (prototype cell) when the user taps the row in the table view?当用户点击表格视图中的行时,如何更新 UITableViewCell(原型单元格)中的标签?
【发布时间】:2014-03-15 23:40:35
【问题描述】:

我正在尝试使用表视图(动态)创建一个简单列表,其中表视图单元格加载了来自简单数组的数据。

当用户点击表格视图中的一行时,我正在尝试更新表格视图单元格上的标签。

问题:由于某种原因,我可以更新所选单元格上的标签,但单元格变为灰色,我无法使用以下方法取消选择:

[tableView deselectRowAtIndexPath:indexPath animated:NO];

但如果我不更新表格视图单元格标签,则取消选择有效!

反之亦然,如果我删除 DeSelect 行语句,则标签更新有效!

我不能让他们同时工作:(

这是我用来更新标签的代码: - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *CellIdentifier = @"ListCell";
 ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];    
 cell.accessoryType = UITableViewCellAccessoryNone;
 cell.TitleLabel.text = @"testing";

有人有什么想法吗?

【问题讨论】:

    标签: ios uitableview


    【解决方案1】:

    无需在 didSelectRowAtIndexPath 方法中使用 dequeueReusableCellIdentifier 创建新单元格,这就是您的文本没有更新的原因。下面的代码应该可以解决您的问题。

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
        ListCell *cell = [tableView cellForRowAtIndexPath:indexPath];   
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.TitleLabel.text = @"testing";
    }
    

    【讨论】:

    • 嗨,这段代码解决了取消选择的问题,但我有一个自定义单元格,我正在尝试更新示例中的标签“TitleLabel”。您的代码覆盖整行。有没有办法替换代码:[tableView cellForRowAtIndexPath:indexPath].textLabel.text = @"New Text!"与我的自定义单元格相关的东西? (我的列表标识符是“ListCell”,自定义标签是“TitleLabel”...非常感谢!!!:)
    • ListCell *cell = [tableView cellForRowAtIndexPath:indexPath];产生 ListCell 和 UITableViewCell 不兼容的编译器警告......但它解决了问题并且现在可以工作了! :)(谢谢)
    【解决方案2】:

    首先,使用 cellForRowAtIndexPath 方法获取选中的单元格

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.TitleLabel.text = @"testing";
    
    }
    

    其次,要禁用单元格的选择样式,请在 cellForRowAtIndexPath 方法中将单元格的 selectionStyle 设置为 UITableViewCellSelectionStyleNone

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多