gpt4 book ai didi

ios - Tableview 动态开关有问题,如果我选择开关并立即打开它,它不会快速打开

转载 作者:搜寻专家 更新时间:2023-11-01 06:54:00 24 4
gpt4 key购买 nike

我创建了一个 UITableView 并根据要求将开关动态添加到每个单元格中。如果我选择一个开关并将其打开并立即选择下一个开关并将其打开,则开关状态会发生变化,并且先前选择的开关正在关闭,只有当我快速选择所有开关时才会发生.

enter image description here

这是我根据数据动态添加所有开关的图像,如果我在第一个开关上,它的数据会将它们加载到另一个表中。但是如果我快速选择所有开关并打开它们,一些开关只会停留在关闭状态。如果我点击表格的外部,它就会消失,如果我再次加载表格,那时候我可以看到所有选定的和之前启用(打开)的开关被关闭(不是全部,而是随机发生的)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if let _ = cell {} else {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
if let d = self.data {
cell?.textLabel?.text = d[indexPath.row]
let switchView = UISwitch(frame: .zero)
switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell?.accessoryView = switchView

}
return cell!
}

func isFolderIsAdded(folderName:String) -> Bool{
for val in listOfSelectedFolder{
if(folderName == val ){
return true
}
}
return false;
}

@objc func switchChanged(_ sender : UISwitch!){
if let d = self.data {
if(sender.isOn){
self.delegate?.selectedSubFolder(name: d[sender.tag])
} else {
self.delegate?.deleteFilesFromFolder(folderName: d[sender.tag])
}
}
}

最佳答案

这是一个重用问题。当您滚动 tableView 时,该单元格将被重新使用。其上的开关将被重置。

您需要遵循 MVC 设计模式。使用模型来帮助您。像这样

class CellModel {
var name = ""
var switchOn = false
}

var dataSource = [CellModel]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
cell.model = dataSource[indexPath.row]
return cell
}
class CustomCell: UITableViewCell {

var model: CellModel? {
didSet {
switchView.isOn = model?.switchOn ?? false
}
}
init(xxxx) {
switchView.addTarget(self, action:#selector(self.switchChanged(_:)), for: .valueChanged)
}


@objc func switchChanged(_ sender : UISwitch!){
model.switchOn = sender.isOn
}
}

关于ios - Tableview 动态开关有问题,如果我选择开关并立即打开它,它不会快速打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037485/

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