[英]Changing custom UIImage in didSelectRowAtIndexPath
我的单元格中有一个自定义UIImage
,当调用didSelectRowAtIndexPath
时需要更改它。 出于某种原因,图像没有改变,我认为这是因为我在方法中声明了单元格。
class CustomCell: UITableViewCell {
@IBOutlet weak var indicator: UIImageView!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
cell.indicator.image = UIImage(named: "newImage")
}
单击单元格时,如何将UIImage
更改为“newImage”?
从索引路径创建单元格
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomCell
cell.indicator.image = UIImage(named: "newImage")
}
您需要创建一个 UIImage 变量并在按下 tableviewcell 时更改该图像变量。
例如...
var imageVar:UIImage = UIImage(named: "IM")
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell?
let ImageView:UIImageView = cell!.viewWithTag(1) as! UIImageView
ImageView.image = imageVar
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.imageVar = UIImage(named: "Image")
self.tableView.reloadData
}
对于 Swift 5
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! MembersCell
cell.member_status.image = YourImage
}
另外,如果在表格视图中的可重用单元格的情况下只想更改一个单元格图像,而其他单元格图像数据不受影响,类似于单选按钮功能。 所以你可以实现如下:-
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {
cell.indicator.image = UIImage(named: "newImage")
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {
cell.indicator.image = UIImage(named: "oldImage")
}
}
然后输出看起来像:-
而另一个:-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.