@interface MyCustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@property (strong, nonatomic) NSString *cellKey;
@end
在cellForRowAtIndexPath Delegate方法中,我正在分配cellKey并向按钮添加一个点击侦听器。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
MyItem *item = [self.data objectAtIndex:row];
NSString *identifier = @"MyCustomCell";
MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
//Give the cell the key
cell.cellKey = item.key;
//add a tap listener
[cell.myButton addTarget:self action:@selector(buttonTaped:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
在buttonTaped处理程序中,我想获取与单击按钮对应的单元格的键:
- (IBAction)buttonTaped:(id)sender
{
//Get the button
UIButton *senderButton = (UIButton *)sender;
//get the super view which is the cell
MyCustomCell *cell = (MyCustomCell *)[senderButton superview];
//get the key
NSString *key = cell.cellKey;
}
然而,当我运行应用程序并单击按钮时,当我使用此错误调用cell.cellKey时应用程序崩溃:
-[UITableViewCellContentView cellKey]: unrecognized selector sent to instance 0x13576240
没有认识到superView属于MyCustomCell类型。那么我怎样才能获得" cellKey"单击按钮的单元格的属性?
由于
答案 0 :(得分:1)
您的按钮实际上已添加到单元格contentView
中,因此您需要在superview
层次结构中再向上导航一次以进入单元格。