ReactiveSwift: How to observe UIView isHidden?
Asked Answered
A

1

6

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.

Aikens answered 11/4, 2017 at 2:45 Comment(0)
L
6

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.

Levorotatory answered 11/4, 2017 at 12:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.