1
我在我的tableViewCell中有一个imageView,我希望在选择时更改它的图像。这是我有它的代码:在UITableViewCell中选择图像(Swift 3 xcode)
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myCell = tableView.cellForRow(at: indexPath) as! TableCell
myCell.resourceIcons.image = UIImage(named: "RubiusResources2")
tableView.deselectRow(at: indexPath, animated: true)
}
代码工作,但在不同的部分再往下的tableView还有些其他行似乎变化。
编辑:
使用意见娄我来到了以下解决方案:
我首先创建一个2D布尔阵列部分和行我的表已经和他们都设置为false量。
var resourceBool = Array(repeating: Array(repeating:false, count:4), count:12)
然后我创建了一个if语句来检查indexPath中的数组是否为false或true。这将是图像状态改变的地方。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableCell
if (global.resourceBool[indexPath.section][indexPath.row] == false) {
myCell.resourceIcons.image = global.systemResourceImages[0]
} else if (global.resourceBool[indexPath.section][indexPath.row] == true) {
myCell.resourceIcons.image = global.systemResourceImages[1]
}
return myCell
}
然后,在didSelectRow函数中,我将indexPath处的数组更改为true,并重新载入tableView数据。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
global.resourceBool[indexPath.section][indexPath.row] = true
tableView.reloadData()
tableView.deselectRow(at: indexPath, animated: true)
}
根据我的理解,对象的状态必须始终位于cellForRow中。
看到我的评论:https://stackoverflow.com/questions/44618366/swift-uicollectionview-cells-arent-停止订购#comment76222954_44618366这对桌面浏览来说是一回事,单元格正在被重用,单元格不能保持状态,图像变化是状态。 – luk2302
有一个单元重用。您需要始终在单元格的prepareForReuse上设置原始背景。基本上,在prepareForReuse上,您应该将单元格中的所有属性设置为原始状态。 – teixeiras
@ luk2302是正确的,这是一个很好的解决方案,但如果您对所有单元格的选定状态使用相同的图像,则将该图像置于imageView突出显示的状态并仅更改所选行行的状态。 并在.image属性中使用正常图像。 –