如何更新约束并确保视图始终位于中心:
@IBOutlet weak var addViewConstraintX: NSLayoutConstraint!
@IBOutlet weak var addViewConstraintY: NSLayoutConstraint!
@IBOutlet weak var addView: UIView!
@IBOutlet weak var english: UITextField!
@IBOutlet weak var chinese: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
addView.layer.cornerRadius = 10.0;
addView.layer.masksToBounds = true;
NotificationCenter.default.addObserver(self, selector: #selector(FirstViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
@objc func keyboardWillShow(_ notification:Notification) {
print("keyboardWillShow")
}
答案 0 :(得分:1)
您需要收听不同的通知:UIKeyboardWillChangeFrame
收到通知时,通知的userInfo字典将包含键盘的新大小。
https://developer.apple.com/documentation/uikit/uiwindow/keyboard_notification_user_info_keys
然后只需将垂直布局约束的常量更改为键盘高度的一半。
答案 1 :(得分:0)
使用viewDidLoad
方法
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
其他地方
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
addView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - keyboardHeight/2)
}
}