我制作了一个在 UITableView 中列出项目的应用程序。当我选择项目并向下滚动直到它们离开屏幕时,它们将在视觉上取消选择,这意味着:
我们设置的复选框图像和背景颜色重置为原始状态。
然而,系统本身确实知道选择了什么,没有选择什么。
代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:TblCell! = self.tableView.dequeueReusableCellWithIdentifier("cell") as TblCell!
cell.lblCarName.text = tableData[indexPath.row]
cell.lblPrice.text = tablePrice[indexPath.row]
if (tableAvailability[indexPath.row] == "NO") {
cell.imgCarName.image = UIImage(named: "nonselectable")
cell.lblPrice.textColor = UIColor(red: 172/255, green: 76/255, blue: 67/255, alpha: 1);
} else {
cell.imgCarName.image = UIImage(named: "deselected")
}
cell.selectionStyle = UITableViewCellSelectionStyle.None;
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let cell:TblCell = tableView.cellForRowAtIndexPath(indexPath) as TblCell
if (tableAvailability[indexPath.row] == "YES") {
println("Row \(indexPath.row) selected")
//var myBackView = UIView(frame: cell.frame)
cell.backgroundColor = UIColor(red: 190/255, green: 225/255, blue: 255/255, alpha: 1);
//cell.selectedBackgroundView = myBackView
cell.imgCarName.image = UIImage(named: "selected")
}
}
func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {
let cell:TblCell = tableView.cellForRowAtIndexPath(indexPath) as TblCell
if (tableAvailability[indexPath.row] == "YES") {
println("Row \(indexPath.row) deselected")
//var myBackView = UIView(frame: cell.frame)
cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1);
//cell.selectedBackgroundView = myBackView
cell.imgCarName.image = UIImage(named: "deselected")
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
知道如何解决这个问题吗?
提前致谢。
最佳答案
在“didSelectRowAtIndexPath”上,您直接在单元格上更改 backgroundColor 和 imgCarName。
当您滚动时,您的单元格将被重复使用!这意味着同一个单元格被销毁并用于呈现新内容。
要跟踪所选内容,您需要将该状态保存在除单元格之外的其他位置,可能在您的 tableAvailability 对象中,或处理单元格内容的任何其他对象中。
关于uitableview - Swift UITableView 在视觉上取消选择滚动上的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880753/