调用KeyboardDidHide时无法更改UIView高度

时间:2017-11-16 07:00:23

标签: ios swift uiview constraints frame

知道为什么当KeyboardDidHide通知发生时我无法更改containerView的高度? KeyboardDidShow中的高度变化非常好,但在KeyboardDidHide中不会改变。此外,如果我在TextFieldDidEndEditing中更改它,它确实会改变,但是对于我需要的东西并不完美。

func setupKeyboardObserver() {
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

@objc func handleKeyboardDidHide() {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

@objc func handleKeyboardDidShow() {

    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height -= 35
        }
    }
}

2 个答案:

答案 0 :(得分:0)

设置新的高度值后尝试layoutIfNeeded()

答案 1 :(得分:0)

设置containerView height

后,请使用以下代码
containerView.updateConstraintsIfNeeded()
containerView.layoutIfNeeded()

希望对你有所帮助