【问题标题】:How do I change a UIImage color when tapping tableview cell?点击 tableview 单元格时如何更改 UIImage 颜色?
【发布时间】:2016-09-12 19:53:25
【问题描述】:

所以我已经坚持了一天左右。点击表格视图单元格时如何更改 UIImage 颜色的颜色?例如,我有一个黑色图像,当我点击一个表格视图单元格时,它会将该图像更改为白色?谢谢!

我尝试使用此代码,但我不知道如何正确实现它!

    let theImageView = UIImageView(image: UIImage(named:"foo")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))
theImageView.tintColor = UIColor.redColor()

【问题讨论】:

  • 你知道如何创建自定义tableViewCell吗?

标签: swift xcode uitableview uiimageview uiimage


【解决方案1】:

看起来你有正确的部分,但不知道在哪里调用它们。您将在 cellForRowAt: 方法中将图像分配给图像视图。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
    cell.imageView.image = UIImage(named:"foo")!.withRenderingMode(.alwaysTemplate)
    return cell
}

然后您将在didSelect 委托方法中更改图像视图的色调颜色。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.imageView.tintColor = newColor
    }
}

【讨论】:

  • 谢谢,我会试试这个!我是否需要为 imageView 创建一个插座才能使我添加的代码正常工作?我也有多个具有不同图像的单元格!点击单元格时如何让它们中的每一个都变白?
  • 如果你使用默认的UITableViewCell类,那么你就不需要做outlets了。如果您使用的是自定义表格视图单元格,那么是的,您需要为自定义单元格的图像视图连接插座。如果您的单元格有多个图像视图,则在didSelect 委托方法中更改每个图像视图的色调颜色。
  • 我使用的是默认表格视图。您能否添加代码以显示如何为每个图像更改它?您在 cellForRow 中输入的代码也不起作用。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多