【发布时间】:2018-05-08 10:05:03
【问题描述】:
我在 UITableView 单元格上嵌入了一个 UISwitch。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if self.users.count > 0 {
let eachPost = self.users[indexPath.row]
let postDate = (eachPost.date as? String) ?? ""
let postTitle = (eachPost.title as? String) ?? ""
cell.detailTextLabel?.text = postDate
cell.textLabel?.text = postTitle
}
if cell.accessoryView == nil{
let switchView : UISwitch = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
cell.accessoryView = switchView
}
return cell
}
我的表有 30 行。当我在可见单元格上选择一个开关然后向下滚动时,默认情况下在列表底部的单元格上选择该开关。我该怎么做才能为我的列表做出正确的选择?
【问题讨论】:
-
能否请您添加您的 cellForRowAt 函数的完整代码?
-
您需要为 indexPath 存储更新的开关值并在 cellForRow 函数中设置 true/false
-
@aBilal17 我已经添加了 cellForRowAt 函数的完整代码。
-
这是因为重用。您必须将值保存在某个数组中,并将它们设置为行的单元格。
-
你能给我更多关于如何做到这一点的细节吗?谢谢