我创建了一个自定义表视图,其中包含自定义单元格, 每个单元格包含一个图像和一个按钮(以及其他文本)
我希望能够在单击按钮时更改UIImageView中的图像, 我能够获得点击事件。然而,我很难改变图像。
我试图获取整个单元格以便使用它来更改图像:
UIButton *senderButton = (UIButton *)sender;
NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:senderButton.tag];
LocationCardCell* cell = (LocationCardCell *) senderButton.superview.superview.superview;
if ([cell.class isSubclassOfClass:[LocationCardCell class]]) {
NSLog(@"cell is RIGHT CLASS!!!");
}else{
NSLog(@"cell is not THE RIGHT CLASS!!!");
}
UIView *cellContentView = (UIView *)senderButton.superview;
LocationCardCell *cell1 = (LocationCardCell *)cellContentView.superview;
if ([cell1.class isSubclassOfClass:[LocationCardCell class]]) {
NSLog(@"cell1 is RIGHT CLASS!!!");
}else{
NSLog(@"cell1 is not THE RIGHT CLASS!!!");
}
有人可以告诉我如何通过点击按钮获取单元格吗?
答案 0 :(得分:2)
将此方法保留在您的武器库中......
- (NSIndexPath *)indexPathWithSubview:(UIView *)subview {
while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
subview = subview.superview;
}
return [self.tableView indexPathForCell:(UITableViewCell *)subview];
}
然后,
- (IBAction)pressed:(id)sender {
NSIndexPath *path = [self indexPathWithSubview:(UIButton *)sender];
LocationCardCell* cell = (LocationCardCell *)[self.tableView cellForRowAtIndexPath:path];
// carry on happily
但不是太开心。一旦你拥有它,你的问题并没有说明你打算用那个细胞做什么。修改tableview单元格的一般方法是修改模型,重新加载单元格,然后在数据源中考虑该更改(tableView:cellForRowAtIndexPath :)。
更常规的模式是使用我们刚刚发现的indexPath取消引用模型,修改它,然后重新加载。