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

问题描述 投票:0回答:1

我在向上移动自定义UIView(基本上是警报)时遇到了一些问题。当我打开键盘时,一切正常,并且警报会按预期向上移动。但是,一旦我在textField中输入数字,警报就会恢复到其原始位置。我不知道为什么会这样。顺便说一句,警报视图已添加到情节提要中,并限制在中心。我已附上一些说明性图片提前致谢。

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)

    }
}

Img Correct

Img Alert after typing

ios swift uiview
1个回答
0
投票

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

@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()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.