ios - 滚动时 UISwitch 正在更改其他单元格上的状态

标签 ios swift uitableview uiswitch

我的表格是这样的

 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
}

}

当我更改任何单元格上的开关状态并滚动时。另一个单元格的开关会在其他单元格滚动时定期更改状态。请帮忙

layout of uiswitch

最佳答案

您需要为每个开关设置带有状态的数据数组,并在您的 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/

相关文章:

ios - 使用 MPMediaPlayer Swift 4 淡入淡出(动画)音量

iphone - 将GLKVector3添加到NSMutableArray

swift - 使用 Swift 过滤 Realm 对象

ios - 从 Storyboard 加载自定义 UITableViewCell

ios - 在 objective-c 的 viewDidAppear 中传递一个字符串

ios - Firebase 2.0 - 存储日期和时区

swift - 在 SwiftUI 中突出显示文本的特定部分

ios - 在 stroybord 检查器中使用方程编辑自动布局 "constant"属性

ios - 如何在 TableView 单元格之间进行分隔

ios - 停止 AVPlayer 在 tableviewcell 中播放