问题描述
我正在尝试选择一个单元格内的图像.这是我的视图控制器中的内容:
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单元格中的选择上更改图像-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!