【发布时间】:2017-06-05 12:47:37
【问题描述】:
这很奇怪:我刚刚建立了一个新的 Single-View iOS 项目并将一个 TableView 放入 Main.storyboard。在这个 TableView 中,我放置了一个 TableViewCell,在这个 Cell 中,我放置了一个 UILabel 和一个 UISwitch。 对于这个 TableViewCell,我创建了一个 CocoaTouchClass MyTableViewCell 并在 Interfacebuilder 中为 TableViewCell 的类设置它。 我将 UILabel 和 UISwitch 的 Outlets 连接到 MyTableViewCell,以及开关的操作。 我还连接了 TableView 的数据源并委托给 ViewController。
所以,我认为,设置表格的基本内容。
我的 ViewController 看起来像这样:
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
}
}
所以,我用一些数据行填充表格,并每隔一秒将 UISwitch 切换为 on。
MyTableViewCell-Class 也没什么特别的:
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)")
}
}
好的,启动 iOS 模拟器,我看到了预期的表格。 40 条 Table-Lines 无法在一个屏幕上显示,因此 TableView 可以自行滚动。
现在:当我更改一个 UISwitch 的状态并拖动 TableView 使更改后的 UISwitch 消失,然后拖动 TableView 使更改后的 UISwitch 再次可见时,它会更改回其初始状态。 Switch 事件按原样触发。
那么,我做错了什么?我错过了什么吗?
我录制了一个 4 秒的屏幕录像来演示发生了什么: http://b-bereich.de/download/swiftSwitch.mov
【问题讨论】:
-
@them Sebastian de Vries 表格视图单元格在您向下滚动时被重复使用。您看到的是打开开关后再次可重复使用的单元格。
标签: ios uitableview swift3