我正在创建一个带有swift的应用程序,并将一个视图控制器子类化,在其中添加了一个敲击手势识别器和一个监听键盘显示的NSNotification。我把键盘WillShow的选择器放在基本视图控制器的一个函数中。然而,当我将视图控制器子类化,并显示键盘时,我的应用程序以NSException终止,它说找不到选择器。有人能解释为什么会发生这种事,以及我该如何解决吗?
以下是我的基本视图控制器中的功能:
override func viewDidLoad() {
super.viewDidLoad()
setNotificationListers()
setTapGestureRecognizer()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setNotificationListers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
func setTapGestureRecognizer() {
let tapped = UITapGestureRecognizer(target: self, action: "closeKeyboard")
tapped.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapped)
}
func closeKeyboard() {
self.view.endEditing(true)
}
func keyboardWillShow() {
self.view.frame.origin.y += CGFloat(keyboardHeight)
}
func keyboardWillHide() {
self.view.frame.origin.y -= CGFloat(keyboardHeight)
}
我没有覆盖子类中的任何内容。什么会被继承,什么不会被继承?
提前感谢您的帮助!
选择器声明需要一个参数,但函数不需要参数。
从选择器声明中删除:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow"), name: UIKeyboardWillShowNotification, object: nil)
或者更改您的功能
func keyboardWillShow(notification: NSNotification) {
self.view.frame.origin.y += CGFloat(keyboardHeight)
}
并对CCD_ 2进行同样的操作。
Selector
方法有一个:
,这意味着您的方法需要一个参数。因此,您应该将两种方法更改为:
func keyboardWillShow(notification: NSNotification) {
self.view.frame.origin.y += CGFloat(keyboardHeight)
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y -= CGFloat(keyboardHeight)
}
无论如何,xCode 7.3已经改变了实现selector
的方式。你可以使用这个伟大的libhttps://github.com/hackiftekhar/IQKeyboardManager以处理键盘向上推。使用起来非常简单。