gpt4 book ai didi

ios - 将 UIView 设置为键盘高度

转载 作者:行者123 更新时间:2023-11-28 21:10:32 27 4
gpt4 key购买 nike

我想将我的 View 底部约束设置为等于键盘高度。键盘在 VC 的生命周期中始终处于事件状态。

但是,当我的 VC 正在加载时,我的 View 以一种奇怪的方式改变了它的高度(如我在 gif 中所示)

在 IB 中,keyboardHeigthConstraint 是 Bottom Layout Guide Top 和我的 View 的约束,并且等于 0

 @IBOutlet weak var keyboardHeigthConstraint: NSLayoutConstraint!

override func viewDidLoad() {
super.viewDidLoad()
cardNumberTextField.becomeFirstResponder()

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
}

func handleKeyboardNotification(notification: NSNotification) {

if let userInfo = notification.userInfo {
let keyboardFrame: CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

DispatchQueue.main.async {
self.keyboardHeigthConstraint.constant = keyboardFrame.size.height
self.view.layoutIfNeeded()
}
}

什么会导致这种奇怪的行为?

enter image description here

最佳答案

您的代码中存在一些问题:

  • cardNumberTextField.becomeFirstResponder() 应该在 viewWillAppear 中调用;
  • 在订阅键盘通知后调用 cardNumberTextField.becomeFirstResponder()
  • 取消订阅 viewDidDisappear 中的键盘通知;
  • 更新约束而不将其包装在 DispatchQueue.main.async 中。

我认为它应该有所帮助。

@IBOutlet weak var keyboardHeigthConstraint: NSLayoutConstraint!

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
cardNumberTextField.becomeFirstResponder()
}

override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
super.viewDidDisappear(animated)
}

func handleKeyboardNotification(notification: NSNotification) {
guard let userInfo = notification.userInfo,
let frameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else {

return
}

let keyboardFrame = frameValue.cgRectValue
keyboardHeigthConstraint.constant = keyboardFrame.height
view.layoutIfNeeded()
}

关于ios - 将 UIView 设置为键盘高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43589873/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com