Search code examples
swiftrx-swiftrx-cocoa

Is there a way yo bind preferredStatusBarStyle with RxCocoa?


I was using following code bind statusBarStyle.

public extension Reactive where Base: UIApplication {

    public var statusBarStyle: Binder<UIStatusBarStyle> {
        return Binder(self.base) { view, attr in
            view.statusBarStyle = attr
        }
    }

}

However this property is deprecated with iOS 9. New document suggests to override preferredStatusBarStyle in view controllers. How can I bind this property?


Solution

  • You can't "bind" to preferredStatusBarStyle because it is a generated property. As you've said, you'll have to override this property and return a value. One approach could be to create a BehaviorRelay property, bind to this instead, and return the value of the relay from your overridden method. You'll also want to make sure to tell the view controller when the status bar style has changed:

    let statusBarStyleRelay = BehaviorRelay<UIStatusBarStyle>(value: .default)
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return statusBarStyleRelay.value
    }
    
    func setupBindings(for statusBarObservable: Observable<UIStatusBarStyle>) {
        statusBarObservable
            .bind(to: statusBarStyleRelay)
            .disposed(by: disposeBag)
    
        statusBarStyleRelay
            .distinctUntilChanged()
            .do(onNext: { [weak self] _ in
                self?.setNeedsStatusBarAppearanceUpdate()
            })
            .subscribe()
            .disposed(by: disposeBag)
    }