教程类型“NSNotification.Name”没有成员“UIResponder”中的 Swift 5 不起作用
Posted
技术标签:
【中文标题】教程类型“NSNotification.Name”没有成员“UIResponder”中的 Swift 5 不起作用【英文标题】:Swift 5 doesn't working method from tutorial Type 'NSNotification.Name' has no member 'UIResponder' 【发布时间】:2020-11-04 09:16:18 【问题描述】:我对编程和 swift 非常陌生,所以我在 YouTube 上学习教程。我按照示例编写代码,但遇到了一个错误。告诉我如何解决它。在教程中,您应该有一个出现和消失的键盘。
import UIKit
class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()
registerForKeyBoardNotification()
deinit
removeKeyBoardNotification()
@IBOutlet weak var scrollViewLogInScreen: UIScrollView!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
@IBAction func logInButtonTapped(_ sender: UIButton)
topTextField.resignFirstResponder()
bottomTextField.resignFirstResponder()
@objc
This code doesn't work with following errors:
Type 'NSNotification.Name' has no member 'UIResponder'
**func registerForKeyboardNotification()
NotificationCenter.default.addObserver(self, selector: #selector(kbWillShow), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(kbWillHide), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
**
This code also doesn't work with following errors:
Type 'NSNotification.Name' has no member 'UIResponder'
**func removeKeyBoardNotification()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name:
NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
**
func kbWillShow(_ notification: Notification)
let userInfo = notification.userInfo
let kbFrameSize = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
scrollViewLogInScreen.contentOffset = CGPoint.init(x: 0, y: kbFrameSize.height)
func kbWillHide()
scrollViewLogInScreen.contentOffset = CGPoint.zero
【问题讨论】:
【参考方案1】:只需删除名称中的NSNotification.Name
NotificationCenter.default.addObserver(self, selector: #selector(kbWillShow), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
一定是这样的:
NotificationCenter.default.addObserver(self, selector: #selector(kbWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
【讨论】:
以上是关于教程类型“NSNotification.Name”没有成员“UIResponder”中的 Swift 5 不起作用的主要内容,如果未能解决你的问题,请参考以下文章
Swift 3 - 如何使用枚举原始值作为 NSNotification.Name?