gpt4 book ai didi

ios - becomeFirstResponder 后不会立即调用 keyboardWillShow 通知

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:50 25 4
gpt4 key购买 nike

我已经实现了 keyboardWillShow:keyboardWillHide: 通知。我正在注册通知,在直接触摸 UITextField 上的屏幕后它们可以正常工作,但是有一个问题。在我的 viewDidLoad 中,注册通知后立即调用 becomeFirstResponder。键盘弹出,但 keyboardWillShow: 没有被调用(如前所述,只是第一次。从您调用该函数注册通知的时间到它被调用的时间似乎有延迟实际上已经注册了,我不应该延迟 becomeFirstResponder 的执行)。有什么想法吗?

@objc func keyboardWillShow(_ notification: NSNotification) {
print("Show")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset: UIEdgeInsets = self.tv_main.contentInset
contentInset.bottom = keyboardSize.height
self.tv_main.contentInset = contentInset
let indexpath = IndexPath(row: 0, section: 0)
self.tv_main.scrollToRow(at: indexpath, at: UITableViewScrollPosition.top, animated: true)
}
}

@objc func keyboardWillHide(_ notification: NSNotification) {
print("Hide")
if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
self.tv_main.contentInset = contentInset

}
}

override func viewDidLoad() {
super.viewDidLoad()
tv_main.delegate = self
tv_main.dataSource = self
tf_search.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
self.tf_search.becomeFirstResponder()
if let placeholder = tf_search.placeholder {
tf_search.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
}
}

最佳答案

您应该在 viewWillAppearviewDidAppear 中调用 becomeFirstResponder

关于ios - becomeFirstResponder 后不会立即调用 keyboardWillShow 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590827/

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