【问题标题】:iOS - How to access custom cell when handle button event in that cell?iOS - 处理该单元格中的按钮事件时如何访问自定义单元格?
【发布时间】:2012-04-13 09:41:37
【问题描述】:

我有一个自定义单元格,在这个自定义单元格中我有一个按钮和一个标签:

#import <UIKit/UIKit.h>

@interface ListCell : UITableViewCell{

}
@property (nonatomic, retain) IBOutlet UIButton* buttonContent;
@property (nonatomic, retain) IBOutlet UILabel* detailContent;

@end

当我处理按钮的点击事件时:

- (IBAction)expandListCell:(id)sender{
    UIButton *button = (UIButton *)sender;
    ListCell *cell = (ListCell *)button.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    cell.detailContent.text = @"FALSE"; // It throw an exception   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"listCell";
    ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];   
    cell.buttonContent.tag = indexPath.row;
    return cell;
}

当我尝试从我的自定义单元格(ListCell)访问任何项目时,它会引发异常:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView detailContent]: unrecognized selector sent to instance 0x8887ca0'

我认为我获得自定义单元格的方式是错误的。有谁知道如何正确获取它?
提前致谢

【问题讨论】:

  • 请也发布 cellForRowAtIndexPath:。
  • 问题 1:您的自定义单元实现中有 @synthesize 吗?问题 2:您为什么首先尝试获取单元格 - 您的按钮应该调用单元格上的方法来告诉它更改文本。您的按钮代码不应直接访问单元格内容。
  • @Mat:我添加了 cellForRowAtIndexPath。 Nick Bull:1,是的,我有合成。 2,我确实需要在点击按钮时访问单元格,我发布的代码是简化的

标签: iphone ios xcode cocoa


【解决方案1】:

你确定你打电话给正确的班级吗? 您确定按钮的超级视图类是 ListCell 类吗?

尝试检查一下:

    // (...)
    ListCell *cell = (ListCell *)button.superview;
    if ([cell.class isSubclassOfClass:[ListCell class]]) {
        ///// just a check for indexPath: /////
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        NSLog(@"current indexPath: %@", indexPath );
        ///////////// END CHECK ///////////////
        cell.detailContent.text = @"FALSE"; 
    }else{
        NSLog(@"NOT THE RIGHT CLASS!!!");
    }

【讨论】:

  • NSIndexPath *indecPath = [self.tableView indexPathForCell:cell]; 行有什么作用?可能是对未使用的变量 indexpath 发出警告
  • @meronix:是的,你是对的,它不是 ListCell 也不是 UITableViewCell。 ListCell *cell = (ListCell *)button.superview.superview;是获得细胞的正确方法。感谢您的回答
  • @Claric PWI:是的,你是对的,它只是为了检查......我从我的项目中粘贴了它,现在我重新添加了一个日志以使其对编辑有意义
【解决方案2】:

好的,很抱歉没有正确回答您的问题,您可以做的只是在将其添加到单元格之前为您的标签视图分配一个 teg,然后在检索时使用

UILabel *name = (UILabel *)[cell viewWithTag:kLabelTag];

并为标签设置文本

【讨论】:

  • detailContent 是自定义属性标签
  • 可能 detailContent 是 ListCell 的一个属性。
猜你喜欢
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多