我在动态tableview中显示一个开关有一个奇怪的问题:其中一个UISwitch实例与左边对齐。一旦切换,它就会恢复正常......一会儿。
重现问题 我可以在物理设备和模拟器上为所有类型的设备重现该问题。出现问题的行取决于设备的屏幕大小:它似乎是第一行在开始时不可见。在小型设备第8行,在较大的iPhone第10行或第11行。当我滚动时,同一行受到影响。
我的代码:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return woordeninlijst.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) as! WoordTableViewCell
cell.woordLabel.text = woordeninlijst[indexPath.row].naam
cell.hulpWoordLabel.text = woordeninlijst[indexPath.row].hulpWoord
var scoreImage = [0: #imageLiteral(resourceName: "score grijs"), 1: #imageLiteral(resourceName: "score oranje"), 2: #imageLiteral(resourceName: "score geel"), 3: #imageLiteral(resourceName: "score groen")]
cell.score1.image = scoreImage[Int(woordeninlijst[indexPath.row].score1)]
cell.score2.image = scoreImage[Int(woordeninlijst[indexPath.row].score2)]
cell.score3.image = scoreImage[Int(woordeninlijst[indexPath.row].score3)]
cell.score4.image = scoreImage[Int(woordeninlijst[indexPath.row].score4)]
cell.score5.image = scoreImage[Int(woordeninlijst[indexPath.row].score5)]
let activeSwitch = UISwitch()
cell.accessoryView = activeSwitch
activeSwitch.addTarget(self, action: #selector(WoordTableViewController.switchChanged(sender:)), for: UIControlEvents.valueChanged)
activeSwitch.tag = indexPath.row
activeSwitch.isOn = woordeninlijst[indexPath.row].isActive
return cell
}
@objc func switchChanged(sender: UISwitch!) {
print("Switch value is \(sender.isOn)")
print("Switch item is \(sender.tag)")
let changeWoord: WoordMO = woordeninlijst[sender.tag]
if changeWoord.isActive == true {
changeWoord.isActive = false}
else {
changeWoord.isActive = true
}
}
任何帮助都非常感激!