Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveSwift: How to observe UIView isHidden?

I'd like to show B UIView iff A UIView is visible. I used ReactiveCocoa 2 in objective-c and tried to find a similar way to observe isHidden property of UIView in ReactiveSwift. I'm still trying to learn the framework and its usage, but couldn't come up with a good solution. I'd appreciate if anyone can give me an advice.

like image 467
REALFREE Avatar asked Apr 11 '17 02:04

REALFREE


1 Answers

Here's the 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 target for UIView`s isHidden property, so you can actually simplify the above code to:

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

Note that the take(during:) is no longer necessary when using <~, as <~ automatically ties disposal of the binding source to the lifetime of the binding target.

like image 89
jjoelson Avatar answered Oct 22 '22 03:10

jjoelson