剑客
关注科技互联网

[iOS] RxKeyboard:观察键盘框架变化的反应式方法库

RxKeyboard

RxKeyboard provides a reactive way of observing keyboard frame changes. Forget about keyboard notifications. It also perfectly works with UIScrollViewKeyboardDismissMode.interactive .

[iOS] RxKeyboard:观察键盘框架变化的反应式方法库

▲ Interactive keyboard dismissing in UITextView.

Getting Started

RxKeyboard provides two Driver s.

/// An observable keyboard frame.
let frame: Driver<CGRect>

/// An observable visible height of keyboard. Emits keyboard height if the keyboard is visible
/// or `0` if the keyboard is not visible.
let visibleHeight: Driver<CGFloat>

Use RxKeyboard.instance to get singleton instance.

RxKeyboard.instance

Subscribe RxKeyboard.instance.frame to observe keyboard frame changes.

RxKeyboard.instance.frame
  .drive(onNext: { frame in
    print(frame)
  })
  .addDisposableTo(disposeBag)

Tips and Tricks


  • :link:
    I want to adjust UIScrollView ‘s contentInset to fit keyboard height.

    RxKeyboard.instance.visibleHeight
      .drive(onNext: { keyboardVisibleHeight in
        scrollView.contentInset.bottom = keyboardVisibleHeight
      })
      .addDisposableTo(disposeBag)

  • :link:
    I want to make UIToolbar move along with the keyboard in an interactive dismiss mode. (Just like the wonderful GIF above!)

    If you’re not using Auto Layout:

    RxKeyboard.instance.visibleHeight
      .drive(onNext: { keyboardVisibleHeight in
        toolbar.frame.origin.y = self.view.height - toolbar.frame.height - keyboardVisibleHeight
      })
      .addDisposableTo(disposeBag)

    If you’re using Auto Layout, you have to capture the toolbar’s bottom constraint and set constant to keyboard visible height.

    RxKeyboard.instance.visibleHeight
      .drive(onNext: { keyboardVisibleHeight in
        toolbarBottomConstraint.constant = -1 * keyboardVisibleHeight
      })
      .addDisposableTo(disposeBag)

    Note: In real world, you should use setNeedsLayout() and layoutIfNeeded() with animation block. See thedemo project for example.

  • Anything else? Please open an issue or make a Pull Request.

Dependencies

  • RxSwift (= 3.0.0-beta.2)
  • RxCocoa (= 3.0.0-beta.2)

Requirements

  • Swift 3
  • iOS 8+

Installation

  • Using CocoaPods :

    pod 'RxKeyboard', '~> 0.1'
  • UsingCarthage :

    github "devxoul/RxKeyboard" ~> 0.1

License

RxKeyboard is under MIT license.

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址