Swift 3 UISwitch no TableViewCell perde o estado ao rolar
Isso é estranho: acabei de configurar um novo projeto iOS de visualização única e colocar um TableView no Main.storyboard. Neste TableView, coloquei um TableViewCell e, nesta célula, coloquei um UILabel e um UISwitch. Para este TableViewCell, criei um CocoaTouchClass MyTableViewCell e o configurei para a classe TableViewCell no Interfacebuilder. Conectei Outlets para o UILabel e UISwitch ao MyTableViewCell, além de uma ação para o switch. Também conectei o dataSource do TableView e deleguei ao ViewController.
Então, como eu penso, coisas básicas para montar uma mesa.
Meu ViewController fica assim:
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
}
}
Portanto, preencho a tabela com algumas linhas de dados e alterno a cada segundo UISwitch para ativado.
A classe MyTableViewCell também não é nada de 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, inicie o iOS-Simulator e vejo a tabela como esperado. As linhas de tabela não cabem em uma tela; portanto, o TableView se torna rolável.
Agora: quando altero o estado de um UISwitch e arrasto o TableView para que o UISwitch alterado fique fora de vista e, em seguida, arrasto o TableView para que o UISwitch alterado fique visível novamente, ele volta ao seu estado inicial. O evento Switch é acionado como deveria.
Então, o que estou fazendo de errado? Estou esquecendo de algo?
Gravei um Screencast de 4 segundos para demonstrar o que está acontecendo:http://b-bereich.de/download/swiftSwitch.mov