Swift 3 UISwitch en TableViewCell pierde estado al desplazarse
Eso es extraño: acabo de configurar un nuevo proyecto de iOS de vista única y puse un TableView en el Main.storyboard. En este TableView puse un TableViewCell y en esta celda, puse un UILabel y un UISwitch. Para este TableViewCell, creé un CocoaTouchClass MyTableViewCell y lo configuré para la clase TableViewCell en Interfacebuilder. Conecté Outlets para UILabel y UISwitch a MyTableViewCell, así como una acción para el conmutador. También conecté el dataSource de TableView y delegué al ViewController.
Entonces, como creo, cosas básicas para configurar una mesa.
Mi ViewController se ve así:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableData = [[String: Bool]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for index in 1...40 {
self.tableData.append([String(index): index%2 == 0])
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
let object = tableData[indexPath.row].first!
cell.myLabel.text = object.key
cell.mySwitch.setOn(object.value, animated: false)
return cell
}
}
Entonces, lleno la tabla con algunas filas de datos y cambio cada segundo UISwitch a encendido.
MyTableViewCell-Class tampoco es nada especial:
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func switched(_ sender: UISwitch) {
print("Switched: \(sender.isOn)")
}
}
Ok, enciende el simulador de iOS y veo la tabla como se esperaba. 40 Table-Lines no caben en una pantalla, por lo que TableView se hace desplazable.
Ahora: cuando cambio el estado de un UISwitch y arrastre el TableView para que el UISwitch modificado se pierda de vista y luego arrastre el TableView para que el UISwitch modificado vuelva a ser visible, vuelve a su estado inicial. El evento Switch se dispara como debería.
Entonces, ¿qué estoy haciendo mal? ¿Me estoy perdiendo de algo?
Grabé un Screencast de 4 segundos para demostrar lo que está sucediendo:http://b-bereich.de/download/swiftSwitch.mov