所以我有这段代码时,我点击UITextField.The UITextField将自动移动显示键盘和移动到UITextField,但问题是,当我点击UITextField的键盘自动移动显示一半的UITextField,如果我再次点击它UITextField将显示完整的UITextField。我认为这个问题是由于UITextField的最高约束,所以它会读取UITextField的顶部约束,然后读取UITextField的底部。
这是我的代码:
@objc func keyboardWillShow(notification:NSNotification){
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.theScrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
theScrollView.contentInset = contentInset
}
@objc func keyboardWillHide(notification:NSNotification){
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
theScrollView.contentInset = contentInset
}
发布于 2018-05-28 15:46:28
请试试这个代码:
class ViewController: UIViewController {
// This constraint ties an element at zero points from the bottom layout guide
@IBOutlet var keyboardHeightConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
// Note that SO highlighting makes the new selector syntax (#selector()) look
// like a comment but it isn't one
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func keyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let endFrameY = endFrame?.origin.y ?? 0
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
if endFrameY >= UIScreen.main.bounds.size.height {
self.keyboardHeightConstraint?.constant = 0.0
} else {
self.keyboardHeightConstraint?.constant = endFrame?.size.height ?? 0.0
}
UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
}
https://stackoverflow.com/questions/-100001605
复制相似问题