2014-05-03 105 views
0

我创建具有定制单元, 每个小区包含一个图像和一个按钮(除其他文本)的自定义表视图如何更改表格单元格中的UIImageView图像,单击单元格上的按钮?

我希望能够以改变的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!!!"); 
       } 

有人可以请让我知道如何去获得从按钮单击单元格?

回答

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来解引用模型,修改模型,然后重新加载。

+0

正确,如果你不更新你的对象模型,而滚动你的对象返回到以前的状态。在你的情况下UIImageView。因为表格视图不会立即加载所有内容。而滚动它一次又一次地从你的对象模型中读取。 – mohacs

+0

优秀,这个工程。非常感谢你 –

相关问题