UIKeyboard
要求
- iOS 8.0+
- Xcode 9.0+
- Swift 4.0+
安装
Cocoa pods
要将UIKeyboard集成到你的Xcode项目中,使用CocoaPods,创建Podfile。在项目根目录下运行以下命令
$ pod init
在出现的Podfile中指定
platform :ios, ‘8.0’
target '<Your Target Name>' do
use_frameworks!
pod 'UIKeyboard'
end
然后,运行以下命令
$ pod install
用法
- 默认情况下,
UIViewController
有名为keyboard
的UIKeyboard
属性,该属性会在键盘出现变化时进行通知。
class UIKeyboardViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Default UIViewController keyboard property
self.keyboard
}
}
- 您可以使用
UIKeyboard
监听器与闭包或代理一起使用。选择一个更方便的方法。
- 使用
UIKeyboardDelegate
extension UIKeyboardViewController: UIKeyboardDelegate {
func keyboardWillShow(with info: UIKeyboard.Info) {
// Posted immediately prior to the display of the keyboard
}
func keyboardDidShow(with info: UIKeyboard.Info) {
// Posted immediately after the display of the keyboard.
}
func keyboardWillHide(with info: UIKeyboard.Info) {
// Posted immediately prior to the dismissal of the keyboard.
}
func keyboardDidHide(with info: UIKeyboard.Info) {
// Posted immediately after the dismissal of the keyboard.
}
}
- 使用闭包
class UIKeyboardViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.keyboard.willShow { (info) in
// Posted immediately prior to the display of the keyboard
}
self.keyboard.didShow { (info) in
// Posted immediately after the display of the keyboard.
}
self.keyboard.willHide { (info) in
// Posted immediately prior to the dismissal of the keyboard.
}
self.keyboard.didHide { (info) in
// Posted immediately after the dismissal of the keyboard.
}
}
}
UIKeyboard.Info
具有以下属性
/// Rect that identifies the ending frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.
public let frame: CGRect
/// Time interval that identifies the duration of the animation in seconds.
public let animationDuration: TimeInterval
/// Animation curve constant that defines how the keyboard will be animated onto or off the screen.
public let animationCurve: UIView.AnimationCurve
/// Animation options constant that defines how the keyboard will be animated onto or off the screen.
public var animationOptions: UIView.AnimationOptions
- 一个简单的示例,使用
info
来改变scrollView
的内容边距
self.keyboard.willShow { (info) in
UIView.animate(withDuration: info.animationDuration, delay: 0, options: info.animationOptions, animations: {
self.scrollView.contentInset.bottom = info.frame.height
}, completion: nil)
}
许可
在 MIT 许可下发布。有关详情,请参阅 LICENSE。