我必须在UI创建期间获得键盘的高度!所以我不能使用监视键盘高度的方法。我只是得到最终的静态高度,而不是动态~~我该怎么做
答案 0 :(得分:3)
我可以告诉你,键盘高度为纵向216像素,横向为162像素,但使用固定键盘高度是不错的选择。从iOS 8开始,用户可以选择不同的第三方键盘并启用或禁用预测短信,这可以使键盘框架更高。
iOS提供了方便的通知类型,可以在视图控制器中观察到。这些通知是:
NSNotification.Name.UIKeyboardWillShow
:在显示键盘之前发布。NSNotification.Name.UIKeyboardDidShow
:在显示键盘后立即发布。NSNotification.Name.UIKeyboardWillHide
:在解除键盘之前发布。NSNotification.Name.UIKeyboardDidHide
:在解除键盘后立即发布。NSNotification.Name.UIKeyboardWillChangeFrame
:在键盘框架发生变化之前发布。NSNotification.Name.UIKeyboardDidChangeFrame
:在键盘框架发生变化后立即发布。您可以通过在视图控制器的viewDidLoad
或viewDidAppear
方法中添加观察者来注册这些通知:
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
另外,请记得将其删除到deinit
/ viewDidDisappear
方法中:
NotificationCenter.default.removeObserver(self,name:NSNotification.Name.UIKeyboardWillShow,object:nil)
创建与观察者关联的方法(在本例中为keyboardWillShow(notification:)
:
func keyboardWillShow(notification : Notification) {
let info:NSDictionary = notification.userInfo! as NSDictionary
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
self.keyboardHeight = Double(keyboardSize.height)
}
参考:https://developer.apple.com/reference/foundation/nsnotification.name
答案 1 :(得分:0)
如果您需要键盘处理的高度,那么我的朋友你这样做是错误的,只需使用这个很酷的library 并写下这是你的app delegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
IQKeyboardManager.sharedManager().enable = true
return true
}
这个库可以处理所有键盘处理的麻烦
答案 2 :(得分:0)
我是在键盘通知后调用的方法中完成的。它看起来像这样:
func keyboardDidShow(notification: NSNotification) {
let keyboardInfo = notification.userInfo
let keyboardRect = keyboardInfo?[UIKeyboardFrameBeginUserInfoKey] as! CGRect
let keyboardSize = keyboardRect.size
var overviewRectangle = self.view.frame
overviewRectangle.size.height += keyboardSize.height
self.overviewScrollView.contentSize = overviewRectangle.size
self.overviewScrollView.setContentOffset(CGPoint.init(x: 0, y: (overviewRectangle.origin.y + keyboardSize.height)), animated: true)
}
func keyBoardDidDisappear(notification: NSNotification) {
let overviewRectangle = self.view.frame
self.overviewScrollView.contentSize = overviewRectangle.size
self.overviewScrollView.setContentOffset(CGPoint.init(x: 0, y: overviewRectangle.origin.y), animated: true)
}