【问题标题】:Can't change image in selected custom cell无法更改所选自定义单元格中的图像
【发布时间】:2012-12-12 16:55:25
【问题描述】:

我创建了一个自定义单元格来显示一个文本和 2 个图像,当用户选择该单元格时,图像应该会改变。我可以访问单元格的属性,但不能更改它们:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    CustomCell *cell = (CustomCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    cell.check.image = setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"];
    [cell.check setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"]]; }

cell.check 是一个 UIImageView

我错过了什么吗?

【问题讨论】:

  • 现在cell.check.image = setImage:是什么鬼?

标签: ios uiimage tableview custom-cell


【解决方案1】:

如果您使用的是自定义单元格,那么您可以覆盖函数 setSelected:animated: 就像这样...

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    if (selected) {
        self.check.image = [UIImage imageNamed:@"1355327732_checkbox-checked"];
    } else {
        self.check.image = nil;
    }
}

那么你不必在 tableView 代码中做任何事情来改变它。它会起作用的。

更好的替代方法是在 self.check 中保持图像相同。然后,您可以相应地将隐藏设置为 YES 或 NO。这也会更高效。

为了让您从表中获得多个选择,然后在 TableViewController 中放置...

self.tableView.allowsMultipleSelection = YES;

这将设置它,以便您可以选择多行。一键选择,一键取消选择。

要获取选定的行,您可以运行...

NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];

【讨论】:

  • 问题是,我需要图像保持不变,但是,当我选择另一行时,前一个被取消选择,图像变回旧的
  • 只需要在tableView中开启allowsMultipleSelection即可。然后,这将设置它,以便一次点击选择单元格,另一次点击取消选择单元格。然后,您可以选择任意数量。
【解决方案2】:

为什么要在同一行调用 setImage 和 cell.check.image?试试这个,看看结果是否相同。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    CustomCell *cell = (CustomCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    //cell.check.image = setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"];
    [cell.check setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"]]; 

}

【讨论】:

    【解决方案3】:

    我注意到您的代码中有两个问题

    1) 这段代码:

    cell.check.image= setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"];

    2) 没有为图片提供扩展名

    替换为:

    cell.check.image= [UIImage imageNamed:@"1355327732_checkbox-checked.png"];

    【讨论】:

    • 使用 UIImage imageNamed: 方法时不需要使用扩展,这样做会导致其他问题,例如找不到@2x 和~ipad 和@2x~ipad 图像。关闭 .png 扩展名,以便为不同的设备使用正确的图像。如果文件名前面确实有空格,以下是正确的? cell.check.image = [UIImage imageNamed:@"1355327732_ checkbox-checked"];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多