UISwitch, добавленный в tableView, выбирается при прокрутке - PullRequest
0 голосов
/ 08 мая 2018

Я вставил UIS-переключатель в ячейку UITableView.

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 голосов
/ 08 мая 2018

Мое решение без создания пользовательского класса:

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
}

Примечание: множественный выбор должен быть включен

...