【发布时间】:2019-11-07 10:30:08
【问题描述】:
我有一个UITableViewCell,其中包含一堆UISwitches。我希望开关根据用户选择的行打开/关闭,数据正在传递到我的单元格但开关状态没有更新。
我使用的是基本的 MVC,Storyboard 有一个 TableView > TableViewCell > Label |界面切换
控制器:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var testList = [1,2,3,4,5]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table.tableFooterView = UIView()
table.delegate = self
table.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell") as! SwitchCell
//Turn them all on at start
cell.setSwitch(rowSelected: true)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell") as! SwitchCell
cell.setSwitch(rowSelected: false)
}
}
开关单元
类 SwitchCell: UITableViewCell {
@IBOutlet weak var uiswitch: UISwitch!
@IBOutlet weak var label: UILabel!
func setCell(number: Int){
label.text = String(number)
}
func setSwitch(rowSelected:Bool) {
uiswitch.setOn(rowSelected, animated: true)
}
}
我知道我可以让 UISwitch 变得难以处理,但我正在考虑在用户选择行时更改它的状态。
【问题讨论】: