当用户点击表视图中的行时,如何更新UITableViewCell(原型单元格)中的标签?

时间:2014-03-15 23:40:35

标签: ios uitableview

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

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

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

[tableView deselectRowAtIndexPath:indexPath animated:NO];

但如果我不更新表视图单元格标签,则DeSelect可以正常工作!

反之亦然,如果删除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";

有人有什么想法吗?

2 个答案:

答案 0 :(得分:2)

没有必要在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";
}

答案 1 :(得分:0)

首先,要获取所选单元格,请使用cellForRowAtIndexPath方法

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

}

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

相关问题