调整UITextView框架以使用UIKeyboardFrameEndUserInfoKey无法正常工作

时间:2018-01-13 17:43:21

标签: ios swift uitextview uikeyboard iphone-x

我正在尝试UITextView中的ViewController,因此当键盘出现时,UITextView不受键盘的阻碍。

我之前使用下面的代码已成功完成此操作,但由于iPhone X现已推出,我的应用程序现在只在iPhone X上正确显示UITextView,而在iPhone等其他设备上显示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)") } 1}}。

class Object1:
   def __init__(self, input=None):
       pass

class Object2:
   def __init__(self, input=None):
       pass

控制台

在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)

enter image description here

有没有人有任何想法可能会出错?

1 个答案:

答案 0 :(得分:1)

将textView的底部约束挂钩为IBOutlet并执行此操作

DependancyProperty

同时删除这两个观察员

@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.textViewBottomCon.constant = 0
    } else {
         self.textViewBottomCon.constant = -1 * ( keyboardViewEndFrame.height + 20.0 )
    } 
    self.view.layoutIfNeeded() 
}