简体   繁体   English

如何在单元格的按钮单击中更改表格单元格中的UIImageView图像?

[英]How to Change an UIImageView Image in a Table cell, on a button click from the cell?

I created a custom table view which has custom cells, Each cell contains an image and a button (amongst other text) 我创建了一个自定义表视图,其中包含自定义单元格,每个单元格包含一个图像和一个按钮(以及其他文本)

I want to be able to change the image in the UIImageView when the button is clicked, I am able to get the click event. 我希望能够在单击按钮时更改UIImageView中的图像,我能够获得单击事件。 I however am having a difficult time changing the image. 然而,我很难改变图像。

I have attempted to get the entire cell in order to change the image using that : 我试图获取整个单元格以使用它来更改图像:

   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!!!");
              }

Can somebody please let me know how to go about getting the cell from the button click? 有人可以让我知道如何从点击按钮获取单元格?

Keep this method in your arsenal... 将此方法保留在您的武器库中......

- (NSIndexPath *)indexPathWithSubview:(UIView *)subview {

    while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
        subview = subview.superview;
    }
    return [self.tableView indexPathForCell:(UITableViewCell *)subview];
}

Then, 然后,

- (IBAction)pressed:(id)sender {

    NSIndexPath *path = [self indexPathWithSubview:(UIButton *)sender];
    LocationCardCell* cell = (LocationCardCell *)[self.tableView cellForRowAtIndexPath:path];

   // carry on happily

But not too happily. 但不是太开心。 You question doesn't state what you plan to do with that cell once you have it. 一旦你拥有它,你的问题就没有说明你计划对那个细胞做什么。 The generally right approach to modifying tableview cells is to modify your model, reload the cell, and then account for that change in the datasource (tableView:cellForRowAtIndexPath:). 修改tableview单元的一般正确方法是修改模型,重新加载单元格,然后在数据源中考虑该更改(tableView:cellForRowAtIndexPath :)。

A more conventional pattern would be to use the indexPath we just found to dereference your model, modify it, then reload. 一个更传统的模式是使用我们刚刚发现的indexPath来取消引用你的模型,修改它,然后重新加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM