滚动时选择添加到tableView的UISwitch

时间:2018-05-08 10:05:04

标签: uiswitch swift4.1

我在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行。当我在可见单元格上选择一个开关然后向下滚动时,在列表底部的单元格上默认选择该开关。如何为列表选择正确的选项?

1 个答案:

答案 0 :(得分:0)

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

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
}

注意:必须启用多项选择