【问题标题】:UISwitch added to a tableView is selected when scrolling滚动时选择添加到 tableView 的 UISwitch
【发布时间】: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 函数的完整代码。
  • 这是因为重用。您必须将值保存在某个数组中,并将它们设置为行的单元格。
  • 你能给我更多关于如何做到这一点的细节吗?谢谢

标签: uiswitch swift4.1


【解决方案1】:

我没有创建自定义类的解决方案:

class MyTableViewController: UITableViewController {
var users: [[String: Any]] = [[String: Any]]()
// This array is used for storring the state for switch from each cell. Otherwise when the cell is reused the state is displayed incorrectly
    var switchArray = [Bool]()
 override func viewDidLoad() {
        super.viewDidLoad()
            self.users = result
            for _ in 0 ..< self.users.count {
                self.switchArray.append(false)
            }
            self.tableView?.reloadData()
        }
    }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    let eachPost = self.users[indexPath.row]
    let postTitle = (eachPost.title as? String) ?? ""
    cell.textLabel?.text = postTitle

    let switchView : UISwitch = UISwitch(frame: .zero)
    switchView.isOn = self.switchArray[indexPath.row]
    cell.accessoryView = switchView

return cell}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    self.switchArray[indexPath.row] = true
let switchView : UISwitch = (tableView.cellForRow(at: indexPath)?.accessoryView) as! UISwitch;
    switchView.isOn = true

}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    self.switchArray[indexPath.row] = false
let switchView : UISwitch = (tableView.cellForRow(at: indexPath)?.accessoryView) as! UISwitch;
    switchView.isOn = false
}

注意:必须启用多选

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2011-11-14
    相关资源
    最近更新 更多