gpt4 book ai didi

swift - 无法识别的选择器发送到实例,通知中心获取键盘大小

转载 作者:行者123 更新时间:2023-11-30 10:50:39 25 4
gpt4 key购买 nike

如果我尝试点击文本字段,则会收到错误,与尝试获取移动 iOS 设备上键盘大小的这几行代码有关。通知中心的代码行位于重写的 ViewDidAppear 内。

 NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillShow:")), name: UIResponder.keyboardDidShowNotification, object: nil)

NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillHide:")), name: UIResponder.keyboardDidHideNotification, object: nil)

func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.bottomConstraint.constant = keyboardSize.height
}
}
}

func keyboardWillHide(notification: NSNotification) {
self.bottomConstraint.constant = 0

}

最佳答案

使用类型安全语法

#selector(keyboardWillShow)

@objc func keyboardWillShow(_ notification: Notification) { ...
<小时/>

但是我强烈建议使用基于现代闭包的语法

NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in
if let userInfo = notification.userInfo,
let keyboardSize = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self?.bottomConstraint.constant = keyboardSize.height
}
}
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] _ in
self?.bottomConstraint.constant = 0
}

关于swift - 无法识别的选择器发送到实例,通知中心获取键盘大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54643496/

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