不再需要手动检查键盘通知和解析键盘出现信息!
一个小型(但很棒)的工具,用于处理 UIKeyboard 在您的视图控制器中出现和消失。
github "nodes-ios/KeyboardHelper" ~> 3.0.0
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: 一个 CGRect,对应于 UIKeyboardFrameBeginUserInfoKey 的值endFrame: 一个 CGRect,对应于 UIKeyboardFrameEndUserInfoKey 的值belongsToCurrentApp: 一个 Bool,对应于 UIKeyboardIsLocalUserInfoKey 的值animationDuration: 一个 Double,对应于 UIKeyboardAnimationDurationUserInfoKey 的值animationCurve: 一个 UIViewAnimationCurve,对应于 UIKeyboardAnimationCurveUserInfoKey 的值animationOptions: 一个 UIViewAnimationOptions,来自 UIKeyboardAnimationCurveUserInfoKey 的值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: 实现示例相同的效果。
用 ❤️ 在 Nodes 制作。
KeyboardHelper 在 MIT 许可证下可用。 有关更多信息,请参阅 LICENSE 文件。