ReactiveSwift: How to observe UIView isHidden?

I would like to show B

UIView iff A

UIView. I used ReactiveCocoa 2 in objective-c and tried to find a similar way to observe a isHidden

UIView property in ReactiveSwift

. I am still trying to learn the structure and its usage, but could not find a good solution. I would be grateful if anyone can give me advice.

+3


source to share


1 answer


Here's a KVO example from the ReactiveSwift readme :

// A producer that sends the current value of `keyPath`, followed by
// subsequent changes.
//
// Terminate the KVO observation if the lifetime of `self` ends.
let producer = object.reactive.values(forKeyPath: #keyPath(key))
    .take(during: self.reactive.lifetime)

      

So, in your case, you can do something like this (haven't actually tried this code, but it should convey the idea):

viewA.reactive.values(forKeyPath: #keyPath(isHidden))
    .take(during: self.reactive.lifetime)
    .startWithValues { hidden in viewB.isHidden = hidden }

      



UPDATE:

I just noticed that ReactiveCocoa includes a binding object for the UIView` isHidden property , so you can simplify the above code:

viewB.reactive.isHidden <~ viewA.reactive.values(forKeyPath: #keyPath(isHidden))

      

Note that it is take(during:)

no longer required in use <~

because it <~

automatically associates the deletion of the binding source with the lifetime of the binding target.

+4


source







All Articles