【问题标题】:Cannot move up custom UIView when keyboard appears出现键盘时无法上移自定义 UIView
【发布时间】:2020-05-19 21:41:21
【问题描述】:

我在移动自定义 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】:

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

    @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()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 2011-12-18
      • 2014-11-15
      • 1970-01-01
      相关资源
      最近更新 更多