【问题标题】:RxSwift: How can I change Bool to ObservableType?RxSwift:如何将 Bool 更改为 ObservableType?
【发布时间】:2019-10-13 02:23:36
【问题描述】:

我是 RxSwift 的新手,我想实现这一目标:

一个titleTextField、一个descTextField、一个confirmButton和一个submitButton。

在titleTextField和descTextField的text.count >= 5并且confirmButton被选中之前submitButton是unEnable的,所以我写了这些代码:

let titleValid = titleTextField.rx.text.orEmpty.map { (text) -> Bool in
    return text.count >= 5
}

let descValid = descTextField.rx.text.orEmpty.map { (text) -> Bool in
    return text.count >= 5
}

let isConfirm = confirmButton.rx.isSelected.asObserver().mapObserver { (selected) -> Bool in
    return selected
}

Observable.combineLatest(titleValid, descValid, isConfirm) { $0 && $1 && $2 }.bind(to: submitButton.rx.isEnabled).disposed(by: disposeBag)

titleValiddescValid 可以很好地工作,但是isConfirm 有一个错误:

Argument type 'AnyObserver<Bool>' does not conform to expected type 'ObservableType'

如何将isConfirm 更改为ObservableType?如何纠正?

注意 RxSwift 的版本是 5.0.0

【问题讨论】:

  • 按钮的isSelected 状态只能输入。您需要观察导致其设置为真/假的任何原因,而不是直接观察它。不要在视图中存储模型状态。是什么导致 isSelected 改变值?
  • @DanielT。用户点击按钮导致 isSelected 更改
  • 如果他们再次点击它会发生什么,isSelected 会变回 false 还是保持 true?
  • @DanielT。点按一次就会更改值

标签: rx-swift


【解决方案1】:

cmets 包含您的答案。重要的是点击confirmButton

let titleValid = titleTextField.rx.text.orEmpty.map { (text) -> Bool in
    return text.count >= 5
}

let descValid = descTextField.rx.text.orEmpty.map { (text) -> Bool in
    return text.count >= 5
}

let isConfirm = confirmButton.rx.tap
    .scan(false) { current, _ in !current }
    .startWith(false)

isConfirm
    .bind(to: confirmButton.rx.isSelected)
    .disposed(by: disposeBag)

Observable.combineLatest(titleValid, descValid, isConfirm) { $0 && $1 && $2 }
    .bind(to: submitButton.rx.isEnabled)
    .disposed(by: disposeBag)

【讨论】:

  • 感谢您的帮助,但是使用您的代码,确认按钮在被录制时将永远被选中。点击确认按钮的功能是:confirmButton.isSelected = !confirmButton.isSelected
  • 不要像使用模型一样使用视图。将它们分开。我已更新代码以切换确认按钮。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多