gpt4 book ai didi

swift - 选择行时 UITableViewCell 不更新 UISwitch

转载 作者:行者123 更新时间:2023-11-28 10:02:45 24 4
gpt4 key购买 nike

我有一个 UITableViewCell,其中包含一堆 UISwitches。我希望开关根据用户选择的行打开/关闭,数据正在传递到我的单元格,但开关状态未更新。

我使用的是基本的 MVC,Storyboard 有一个 TableView > TableViewCell > Label |界面切换

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: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 变得棘手,但我正在考虑在用户选择行时更改它的状态。

最佳答案

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)
}

关于swift - 选择行时 UITableViewCell 不更新 UISwitch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58746750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com