我在项目中使用RxSwift
和RxCocoa
。
我有一个UITextField
名为“ lastNameTF”,还有一个UILabel
名为“ lastNameTitle”。
我想知道是否有任何方法可以使用isHidden
将lastNameTitle的isHidden
值设置为等于lastNameTF的RxSwift
值。
答案 0 :(得分:1)
我相信您可以按照此处所述使用KVO- https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md#kvo
答案 1 :(得分:1)
使用KVO非常容易。 Here is an example完全是您要尝试做的事情,而无需使用RxSwift(不知道那是什么...)
这是要点
class ViewController: UIViewController {
private var lastNameTextFieldHiddenContext = 0
private var lastNameObservingView:UIView? = nil
@IBOutlet weak var lastNameLabel: UILabel!
@IBOutlet weak var lastNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// add the observer
lastNameTextField.addObserver(
self,
forKeyPath: "hidden",
options: [.new],
context: &self.lastNameTextFieldHiddenContext
)
}
/// function will be called whenever an added observer is triggered
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
// make sure it is our text field isHidden observer
if context == &self.lastNameTextFieldHiddenContext {
// get the new value that was set
if let newValue = change?[NSKeyValueChangeKey.newKey] as? Bool {
// do what needs to be done when the observer is triggered
self.lastNameLabel.isHidden = newValue
}
}
}
deinit {
// remove the observer
if let view = self.lastNameObservingView {
view.removeObserver(self, forKeyPath: "hidden")
self.lastNameObservingView = nil
}
}
@IBAction func showHideButtonAction(_ sender: Any) {
self.lastNameTextField.isHidden = !self.lastNameTextField.isHidden
}
}
答案 2 :(得分:0)
如果您仍然需要简单的RxSwift方法,请尝试以下操作:
// Controls are visible by default (isHidden = false)
let isControlHidden = BehaviorRelay<Bool>(value: false)
override func viewDidLoad() {
super.viewDidLoad()
let isHiddenDriver = self.isControlHidden.asDriver()
isHiddenDriver
.drive(self.lastNameTitle.rx.isHidden)
.disposed(by: disposeBag)
isHiddenDriver
.drive(self.lastNameTF.rx.isHidden)
.disposed(by: disposeBag)
}
由于两个控件的可视性都需要彼此绑定,因此可以使用“主题”或“中继”来实现,在这种情况下为“ ControlHidden”。因此,如果您想显示/隐藏它,则只需发出一个新信号:
@IBAction func hide(_ sender: Any) {
self.isControlHidden.accept(true)
}
@IBAction func show(_ sender: Any) {
self.isControlHidden.accept(false)
}