gpt4 book ai didi

ios - Swift 键盘避免 View 无法按预期工作

转载 作者:行者123 更新时间:2023-11-28 10:44:09 25 4
gpt4 key购买 nike

enter image description here

在上面的 GIF 中,loginMenu 应该是一个键盘避免 View 。它永远不会被键盘覆盖。当开始编辑这些文本字段中的任何一个时,loginMenu 确实会“向上推”,但是,在编辑后,loginMenu 会返回到其原始位置。这里有什么问题?这是我的代码:

import UIKit;

class LoginScreenViewController: UIViewController {
@IBOutlet weak var loginMenu: UIView!;

override func viewDidLoad() {
super.viewDidLoad();

NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillChange(notification:)),
name: .UIKeyboardWillChangeFrame,
object: nil
);
}

override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self);
}

@objc func keyboardWillChange(notification: Notification) {
let keyboardHeight = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height;
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.loginMenu.frame.origin.y = UIScreen.main.bounds.height - keyboardHeight - self.loginMenu.frame.height;
});
}
}

最佳答案

这里是解决方案,创建loginMenu View 的底部布局约束引用

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var loginMenu: UIView!

override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

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

@objc func handleKeyboardNotification(_ notification: Notification) {

if let userInfo = notification.userInfo {

let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue

let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0

UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}

Demo Example

关于ios - Swift 键盘避免 View 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250313/

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