0

我在 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 行。当我在可见单元格上选择一个开关然后向下滚动时,默认情况下在列表底部的单元格上选择该开关。我可以做些什么来为我的列表做出正确的选择?

4

1 回答 1

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
}

注意:必须启用多选

于 2018-05-08T17:06:30.683 回答