出现键盘时无法向上移动自定义 UIView



我在向上移动自定义 UIView 时遇到了一些问题,基本上是一个警报。 当我打开键盘时,一切正常,警报会正常向上移动。 但是,一旦我在文本字段中对某些内容进行数字运算,警报就会回退到其原始位置。 我不知道为什么会发生这种情况。顺便说一句,警报视图被添加到情节提要中并限制在中心。 我附上了一些解释性图片 提前谢谢。

class AlertViewController: UIViewController {
@IBOutlet var AlertView: UIView! //Alert View storyboard outlet
override func viewDidLoad() { 
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: 
UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification){
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
// if keyboard size is not available for some reason, don't do anything
return
}
let keyBoardTop = self.view.frame.height - keyboardSize.height
let bottomOfAlertView = AlertView.convert(AlertView.bounds, to: self.view).maxY;
print("keyBoardTop: (keyBoardTop)")
print("BottomOfAlertView: (bottomOfAlertView)")
print(AlertView.frame.origin.y)
AlertView.frame.origin.y = AlertView.frame.origin.y - (bottomOfAlertView - keyBoardTop)
}
}

图像校正

输入后图像警报

尝试像这样更改警报的底部约束怎么样

@objc func handleShowKeyboard(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardOffset = keyboardRectangle.height
if AlertView.viewBottomAnchor.constant == 0 {
AlertView.viewBottomAnchor.constant -= (keyboardOffset - self.view.safeAreaInsets.bottom)
AlertView.layoutIfNeeded()
}
}
}

最新更新