简体   繁体   English

表格单元格Rxswift上的开关按钮

[英]Switch button on tableview cell Rxswift

I'm trying to add a switch change state action to each tableview cell on my tableview, The problem is that the first time I run the application the state action gets called for each cell created. 我试图将切换更改状态操作添加到我的表视图上的每个表视图单元,问题是我第一次运行该应用程序时,将为创建的每个单元调用状态操作。 Has an example when I initially have 5 items on the database, the first time I load the tableview the switch will be called 5 times. 有一个示例,当我最初在数据库上有5个项目时,第一次加载tableview时,该开关将被调用5次。 What I want is an action function, outside the binding, to be called ONLY when the user has clicked the switch. 我想要的是在用户单击开关时才在绑定之外调用动作函数。

Here is the code for the tableview cell: 这是tableview单元格的代码:

class SensorCell: UITableViewCell {

    @IBOutlet weak var txtIndex: UILabel!
    @IBOutlet weak var txtSensorItem: UILabel!
    @IBOutlet weak var sensorSwitch: UISwitch!
    var cellBag = DisposeBag()

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func configure(withViewModel viewModel: SensorItemPresentable) -> (Void) {

        txtIndex.text = viewModel.id!
        txtSensorItem.text = viewModel.textValue!
        sensorSwitch.isOn = viewModel.status!
    }
}

Here is the code when I do the tableview binding: 这是我执行tableview绑定时的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    let nib = UINib(nibName: "SensorCell", bundle: nil)

    tableViewItems.register(nib, forCellReuseIdentifier: identifier)

    viewModel = SensorViewModel()

    self.viewModel?.items.asObservable().bind(to: self.tableViewItems.rx.items(cellIdentifier: identifier, cellType: SensorCell.self)) { index, item, cell in


        cell.sensorSwitch.rx.isOn
            .subscribe({ status in
                //on first time loading the view, if my database has 5 items it will run this 5 times
            print("cell switch set to: \(status)")

            })
            .disposed(by: cell.cellBag)


        cell.configure(withViewModel: item)

        }.disposed(by: bag)

}
cell.sensorSwitch.rx
            .isOn.changed //when state changed
            .debounce(0.8, scheduler: MainScheduler.instance) //handle rigorous user switching
            .distinctUntilChanged().asObservable() //take signal if state is different than before. This is optional depends on your use case
            .subscribe(onNext:{[weak self] value in
                //your code
            }).disposed(by: cell.cellBag)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM