【发布时间】:2018-01-13 17:43:21
【问题描述】:
我试图在我的ViewController 中只添加UITextView,所以当键盘出现时,UITextView 不会被键盘挡住。
我之前已经使用下面的代码成功地做到了这一点,但是自从 iPhone X 推出后,我的应用程序现在只能在 iPhone X 和其他设备(如 iPhone)上正确显示 UITextView,它会阻碍 UITextView。
NotificationCenter.default.addObserver(self, selector: #selector(TextViewController.adjustForKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TextViewController.adjustForKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TextViewController.adjustForKeyboard(_:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TextViewController.adjustForKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
@objc func adjustForKeyboard(_ notification: Notification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == Notification.Name.UIKeyboardWillHide {
self.textView.contentInset = UIEdgeInsets.zero
} else {
self.textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}
self.textView.scrollIndicatorInsets = self.textView.contentInset
let selectedRange = self.textView.selectedRange
self.textView.scrollRangeToVisible(selectedRange)
print("Keyboard End Frame = \(keyboardScreenEndFrame) and Keyboard View End Frame = \(keyboardViewEndFrame)")
}
控制台
在 iPhone X 上运行
键盘结束帧 = (0.0, 479.0, 375.0, 333.0) 和键盘视图结束 帧 = (0.0, 479.0, 375.0, 333.0)
在 iPhone 8 上运行
键盘结束帧 = (0.0, 409.0, 375.0, 258.0) 和键盘视图结束 帧 = (0.0, 409.0, 375.0, 258.0)
有人知道可能出了什么问题吗?
【问题讨论】:
标签: ios swift uitextview uikeyboard iphone-x