【问题标题】:Can't Change UIView Height When KeyboardDidHide is called调用 KeyboardDidHide 时无法更改 UIView 高度
【发布时间】:2017-11-16 07:00:23
【问题描述】:

知道为什么在 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
        }
    }
}

【问题讨论】:

  • 是不是因为if UIScreen.main.nativeBounds.height == 2436的条件?
  • @Amit 不,它到达了代码。如果你打印高度,你得到的高度应该是它只是在视觉上不会改变

标签: ios swift uiview constraints frame


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    设置容器视图高度后使用以下代码

    containerView.updateConstraintsIfNeeded()
    containerView.layoutIfNeeded()
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      相关资源
      最近更新 更多