2015-04-25 163 views
2

我有一个关于UITAbleViewCell的问题。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"; 
} 

后,我点击所需的细胞,没有任何反应......

为什么如我所料不工作?另外,我应该怎么做才能使它工作?

回答

1

试试这个:

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

你应该问UITableView的细胞,而不是直接要求其委托(self在你的代码)。导致其代表可能会取消或创建新的单元格,而不是让您选择单元格。

+0

这是我做不成功(检查示例代码)... –

+0

@TomKortney仔细阅读我的代码。我直接发送消息给'tableView',而不是'self'。 – liushuaikobe

+0

据我所见,这个答案是最简单的答案。谢谢! –

2

你必须创建单元状态e.g一些基础模型:

@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对象(这只是你的脚手架)。

+0

你看,有一个问题,我不仅需要改变一个文本。我还需要更改单元格文本标签的文本颜色和单元格背景颜色... –

+0

@TomKortney对于这些类型的东西,我建议使用某种模型来保存每个单元格的数据。然后你可以在模型中定义颜色,文字等。另一种选择是让另一个具有相同大小的数组保持布尔值,告诉您单元格是否为第一种样式或第二种样式。然后你可以在你的'cellForRowAtIndexPath'方法中添加一个if语句来根据该布尔值设置样式。 – Kyle

+0

有一个选项。但我想知道为什么我的方式不起作用?这似乎是好的... –

相关问题