KeyboardHelper
无需再手动检查键盘通知和解析键盘外观信息!
一个处理视图控制器中 UIKeyboard 出现和消失的小但非常酷的工具。
📦 安装
Carthage
github "nodes-ios/KeyboardHelper" ~> 3.0.0
CocoaPods
pod 'KeyboardHelper', '~> 3.0.0'
旧版本
与较低 Swift 版本兼容的最新版本
Swift 4:
~> 2.0.0
Swift 3:== 1.2.1
Swift 2.3:== 0.10.0
Swift 2.2:== 0.9.4
🔧 设置
在你的 UIViewController 中实现 KeyboardHelperDelegate
。
class ViewController: UIViewController, KeyboardHelperDelegate
添加一个 KeyboardHelper
私有变量,初始化它并将其设置为目标。
private var keyboardHelper : KeyboardHelper?
func viewDidLoad() {
...
self.keyboardHelper = KeyboardHelper(delegate: self)
...
}
在 KeyboardHelperDelegate
中实现两个方法
public func keyboardWillAppear(_ info: KeyboardHelper.KeyboardAppearanceInfo)
public func keyboardWillDisappear(_ info: KeyboardHelper.KeyboardAppearanceInfo)
这两种方法都接受一个 KeyboardAppearanceInfo
对象作为参数,它基本上是 UIKeyboardWillShowNotification
和 UIKeyboardWillHideNotification
通知中 userInfo
字典的包装。
这两个代理方法的实现示例之一是
func keyboardWillAppear(_ info: KeyboardAppearanceInfo) {
UIView.animate(withDuration: TimeInterval(info.animationDuration),
delay: 0,
options: info.animationOptions,
animations: {
let insets = UIEdgeInsetsMake(0, 0, info.endFrame.size.height, 0)
self.scrollView.contentInset = insets
self.scrollView.scrollIndicatorInsets = insets
},
completion:nil)
}
func keyboardWillDisappear(_ info: KeyboardAppearanceInfo) {
UIView.animate(withDuration: TimeInterval(info.animationDuration),
delay: 0,
options: info.animationOptions,
animations: {
let insets = UIEdgeInsetsZero
self.scrollView.contentInset = insets
self.scrollView.scrollIndicatorInsets = insets
},
completion:nil)
}
KeyboardAppearanceInfo
对象具有以下属性
beginFrame
:对应于UIKeyboardFrameBeginUserInfoKey
的CGRect
endFrame
:对应于UIKeyboardFrameEndUserInfoKey
的CGRect
belongsToCurrentApp
:对应于UIKeyboardIsLocalUserInfoKey
的Bool
animationDuration
:对应于UIKeyboardAnimationDurationUserInfoKey
的Double
animationCurve
:对应于UIKeyboardAnimationCurveUserInfoKey
的UIViewAnimationCurve
animationOptions
:对应于UIKeyboardAnimationCurveUserInfoKey
的UIViewAnimationOptions
KeyboardAppearanceInfo
还有一个便利方法 animateAlong:completion:
,可以像这样使用
func keyboardWillAppear(info: KeyboardAppearanceInfo) {
info.animateAlong({ () -> Void in
let insets = UIEdgeInsetsMake(0, 0, info.endFrame.size.height, 0)
self.scrollView.contentInset = insets
self.scrollView.scrollIndicatorInsets = insets
}) { finished in }
以获得与上面初始的 keyboardWillAppear:
实现示例相同的效果。
👥 致谢
由...
📄 许可证
KeyboardHelper 根据 MIT 许可证提供。有关更多信息,请参阅 LICENSE 文件。