2012-04-13 88 views
0

我有一个自定义单元格,并在此自定义单元格我有一个按钮和一个标签:iOS - 如何在该单元格中处理按钮事件时访问自定义单元格?

#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' 

我想我得到自定义单元格的方式是错误的。任何人都知道如何正确地得到它?
预先感谢

+0

请张贴的cellForRowAtIndexPath:太。 – Mat 2012-04-13 09:51:29

+0

问题1:您的自定义单元实现中是否有'@ synthesize'?问题2:你为什么要首先获取单元格 - 你的按钮应该调用单元格上的方法来告诉它更改文本。您的按钮代码不应直接访问单元格内容。 – 2012-04-13 09:57:39

+0

@Mat:我添加了cellForRowAtIndexPath。尼克布尔:1,是的,我已经合成。 2,当按钮被点击时,我确实需要访问单元格,我发布的代码被简化了 – Dranix 2012-04-13 09:59:05

回答

4

你确定你在调用正确的类吗? 你确定你的按钮的超级视图类是一个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!!!"); 
    } 
+1

什么行**'NSIndexPath * indecPath = [self.tableView indexPathForCell:cell];'** dose there?可能会给出未使用变量索引路径的警告 – 2012-04-13 09:59:31

+1

@meronix:是的,对,它不是ListCell和UITableViewCell。 ListCell * cell =(ListCell *)button.superview.superview;是获得细胞的正确方法。谢谢你的回答 – Dranix 2012-04-13 10:07:46

+0

不客气... – meronix 2012-04-13 10:18:44

1

好,我知道了遗憾没有得到你的问题正确,你能做的仅仅是一个TEG分配给您的标签视图之前将其添加到单元格,然后在retrive的什么时间只是使用

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

并设置标签的文字

+0

detailContent是一个自定义属性标签 – meronix 2012-04-13 09:56:10

+0

可能detailContent是ListCell的一个属性。 – Mat 2012-04-13 09:57:31

相关问题