在TableView单元格中的选择上更改图像

编程入门 行业动态 更新时间:2024-10-28 19:26:45
本文介绍了在TableView单元格中的选择上更改图像-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试选择一个单元格内的图像.这是我的视图控制器中的内容:

I am trying to change an image within a cell when it is selected. Here is what I have in my view controller:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell cell.bgImage.image = UIImage(named: "second_image") }

这是我设置图像的地方

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell cell.bgImage.image = UIImage(named: "first_image") }

当我选择单元格时,图像不会更新.我如何使它工作?

When I select the cell, the image does not update. How do I get this to work?

推荐答案

问题可能是您正在调用 dequeueReusableCellWithIdentifier .尝试改用 cellForRowAtIndexPath ((a 此处的文档).这将为您提供对当前单元格的引用,而不是对新的可重用单元格的引用.

The issue is probably that you are calling dequeueReusableCellWithIdentifier. Try using cellForRowAtIndexPath instead (documentation about it here). This will give you a reference to the current cell, rather than a reference to a new reusable cell.

因此,根据您上面的代码:

So, according to your code above:

let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell

此类型转换是关键,因为 cellForRowAtIndexPath 返回 UITableViewCell ,该成员将没有 bgImage 成员.

This typecast is critical because cellForRowAtIndexPath returns UITableViewCell, which will not have the bgImage member.

此外,通过添加 @IBOutlet,确保您的 CustomTableViewCell 类中具有一个名为 bgImage 的成员,该成员是 UIImageView 强大的var bgImage:UIImageView!,并且说 IBOutlet 已连接到您的Storyboard/xib中.

Also, make sure that you have a member called bgImage that is a UIImageView in your CustomTableViewCell class by adding @IBOutlet strong var bgImage: UIImageView!, and that said IBOutlet is connected in your storyboard/xib.

更多推荐

在TableView单元格中的选择上更改图像

本文发布于:2023-11-26 20:24:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635066.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元格   图像   TableView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!