在TableView单元格中的选择上更改图像-Swift [英] Change image on select within tableview cell - Swift

查看:46
本文介绍了在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单元格中的选择上更改图像-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆