我的表格是这样的
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 200
}
我的 tableviewcell 看起来像这样
class Cell: UITableViewCell {
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
}
}
当我更改任何单元格上的开关状态并滚动时。另一个单元格的开关会在其他单元格滚动时定期更改状态。请帮忙
最佳答案
您需要为每个开关设置带有状态的数据数组,并在您的 didSelect 方法中更改开关的数据模型,然后在 cellForRow 中从数组获取开关状态,并且您的 viewController 需要为 SwitchControlDelegate
class UIViewController:SwitchControlDelegate{
var array = [Bool](count: 200, repeatedValue:false)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
cell.switchControl.isOn = array[indexPath.row]
cell.switchDelegate = self
cell.index = indexPath.row
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 200
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
array[indexPath.row] = !array[indexPath.row]
}
func switchChangeStateWithIndex(index:Int){
array[index] = !array[index]
}
这将在您单击单元格时更改开关状态,如果您需要在更改开关控件时更改状态,则需要委托(delegate)更新 viewController 中的数据模型
在你的单元格文件中:
protocol SwitchControlDelegate: class {
func switchChangeStateWithIndex(index:Int)
}
class Cell: UITableViewCell {
var index:Int = 0
weak var switchDelegate: SwitchControlDelegate?
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 valueChanged(_ sender: AnyObject) {
switchDelegate?.switchChangeStateWithIndex(index:index)
}
}
你需要用这个函数 valueChanged 来匹配你的开关控件的 Action 值变化,所以每次当你改变开关状态时,单元格都需要调用 func value Changed
关于ios - 滚动时 UISwitch 正在更改其他单元格上的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45856925/