表格单元格Rxswift

时间:2018-07-06 08:55:09

标签: ios swift reactive-programming rx-swift rx-cocoa

我正在尝试向我的表视图上的每个表视图单元格添加一个开关更改状态操作,问题是我第一次运行该应用程序时,将为创建的每个单元格调用状态操作。 有一个示例,当我最初在数据库上有5个项目时,第一次加载tableview时,该开关将被调用5次。 我想要的是绑定功能之外的动作功能,当用户单击开关时,该功能将被称为

这是表格视图单元格的代码:

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!
    }
}

这是我进行表格视图绑定时的代码:

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)

}

1 个答案:

答案 0 :(得分:3)

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)