我有一个UITableViewCell
,其中包含一堆UISwitches
。我希望开关根据用户选择的行来打开/关闭,数据正在传递到我的单元格,但是开关状态未更新。
我正在使用基本的MVC,情节提要具有TableView> TableViewCell>标签| UISwitch
Controller:
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
类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变得难以处理,但是我正在考虑在用户选择行时更改其状态。
首先,我们不使cell
方法中的didSelectRowAt
出队。绝对不要那样做。这将使一个全新的单元出队,并且不会反映您在其中所做的任何更改。
因此删除tableView(_: didSelectRowAt:)
方法的代码。
其次,您可以使用UISwitch
这样的方法,根据SwitchCell's
定义中的单元格选择简单地处理setSelected(_:animate:)
状态,
class SwitchCell: UITableViewCell {
@IBOutlet weak var uiswitch: UISwitch!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
uiswitch.setOn(selected, animated: true)
}
//rest of the code...
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell") as! SwitchCell
cell.setSwitch(rowSelected: false)
}
不正确。使用此代码,您不会选择所需的单元格。
您应该这样做:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let cell = tableView.cellForRow(at: indexPath) as! SwitchCell
cell.setSwitch(rowSelected: false)
}