KeyboardAdjustable
KeyboardAdjustable 考虑到我们在键盘出现时调整视图的常见三种方式
- 当您有一个 ScrollView 并且在键盘出现时您想更改其 contentInset
- 当您有一个 bottom constraint 为 UIView 时,您希望在键盘出现时更改它的值
- 当您在视图中有多个约束,并且在键盘出现时想更改它们的值
只需一行代码,您就能处理这些场景,而无需在您的 UIViewController 中实现键盘观察者。
使用方法
- 在您的 UIViewController 文件中导入 KeyboardAdjustable
- 将 KeyboardAdjustable 协议添加到您的 UIViewController
- 在 viewDidLoad 中设置 KeyboardAdjustingStrategy
注意:请确保您在 viewDidLoad 中调用 registerForKeyboardNotifications()
,并在 viewDidDisappear 中调用 unregisterForKeyboardNotifications()
示例
class SingleConstraintViewController: UIViewController, KeyboardAdjustable {
var keyboardAdjustingStrategy: KeyboardAdjustingStrategy?
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Register for keyboard notifications
registerForKeyboardNotifications()
// Set your desired strategy to adjust the view when the keyboard appears
self.keyboardAdjustingStrategy = .singleConstraint(
constraint: bottomConstraint,
originalConstant: bottomConstraint.constant,
spaceAboveKeyboard: 20)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Unregister for keyboard notifications
unregisterForKeyboardNotifications()
}
}
此 Pod 还包含一个示例项目
要运行示例项目,克隆仓库,然后首先从 Example 目录运行 pod install
示例
带有滚动视图
单约束
多约束
需求
Swift 4.2
安装
KeyboardAdjustable 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'KeyboardAdjustable'
如果您在上面的命令中遇到问题, 请尝试运行 pod repo update
然后再试
作者
Cesar Bess, [email protected]
许可
KeyboardAdjustable 在 MIT 许可下提供。有关更多信息,请参阅 LICENSE 文件。