col*_*ole 1 uitableview uiswitch ios swift
我的桌面视图看起来像这样
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
}
Run Code Online (Sandbox Code Playgroud)
我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
当我更改任何单元格上的开关状态并滚动时。另一个单元格的开关周期性地在其他单元格的滚动时改变状态。请帮忙
您需要拥有每个开关的状态数据数组,并在 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]
}
Run Code Online (Sandbox Code Playgroud)
当您单击单元格时,这将更改开关状态,如果您需要在更改开关控制时更改状态,您将需要委托来更新 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)
}
}
Run Code Online (Sandbox Code Playgroud)
您需要将开关控件的动作值更改与此函数 valueChanged 相匹配,因此每次更改开关状态单元格时都需要调用 func value Changed
| 归档时间: |
|
| 查看次数: |
1461 次 |
| 最近记录: |