KeyboardAdjuster 提供一个可直接使用的 UILayoutGuide
,帮助您调整视图以避免与键盘冲突。就这么简单。经过实战检验,易于集成到任何项目中--无论是 Storyboards 还是代码,都无关紧要。
KeyboardAdjuster 是从 LHSKeyboardAdjusterSwift 版本的迁移,该版本推荐用于 Objective-C 编写的项目。
要求
- 自动布局
- iOS 9.0-11.2+
安装
KeyboardAdjuster 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod "KeyboardAdjuster", "~> 3"
使用方法
-
在您的视图控制器文件中导入
KeyboardAdjuster
。import KeyboardAdjuster
-
确定哪个视图您想将其固定到键盘顶部--它可能是
UIScrollView
、UITableView
或UITextView
。然后,在您设置视图约束的地方,使用keyboardLayoutGuide
属性创建一个greaterThanOrEqualTo
约束到您想调整大小的视图的底部class MyViewController: UIViewController { func viewDidLoad() { super.viewDidLoad() // ... // Your Auto Layout code here // ... tableView.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor).isActive = true tableView.bottomAnchor.constraint(greaterThanOrEqualTo: keyboardLayoutGuide.topAnchor).isActive = true } }
注意:如果您正在使用iOS 11,并且您的视图正在使用
safeAreaLayoutGuide
来设置约束,请点击此处查看另一种方法。func viewDidLoad() { super.viewDidLoad() tableView.bottomAnchor.constraint(lessThanOrEqualTo: keyboardLayoutGuide.topAnchor).isActive = true }
-
完成!每当键盘出现时,您的视图将自动调整大小。
可选功能
KeyboardAdjuster还允许您在键盘状态改变时提供回调或指定是否要动画化过渡(默认为动画)。如果您想利用这些功能,只需让您的UIViewController
遵守KeyboardAdjusterOptions
,如下所示
class MyViewController: UIViewController, KeyboardAdjusterOptions {
var animateKeyboardTransition = true
func keyboardWillHideHandler() {
print("Hiding keyboard...")
}
func keyboardWillShowHandler() {
print("Showing keyboard...")
}
}
如何工作
KeyboardAdjuster为键盘出现和消失注册了NSNotificationCenter回调。当键盘出现时,它会从通知中获取键盘大小以及键盘动画的时间,并将应用应用于keyboardLayoutGuide
属性。
支持KeyboardAdjuster
支持KeyboardAdjuster,使其与最新版本的iOS保持同步等,需要花费大量时间!因此,如果您是一个从中受益的开发者,请通过star该仓库来支持它。这会增加其在GitHub搜索中的可见性,并鼓励其他人做出贡献。🙏🏻
作者
授权协议
KeyboardAdjuster遵循Apache 2.0 授权协议。更多信息请参阅授权协议文件。