Swift:对ViewController进行子类化并添加目标?

时间:2016-04-01 03:53:10

标签: ios swift inheritance

我正在使用swift创建一个应用程序,我将一个视图控制器子类化,其中我添加了一个轻敲手势识别器和一个侦听键盘出现的NSNotification。我将keyboardWillShow的选择器放在基本视图控制器的函数中。然而,当我将我的视图控制器子类化,并且我有键盘显示时,我的应用终止了一个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)
}

我没有覆盖子类中的任何内容。什么将被继承,什么不会?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您的选择器声明需要参数,但您的函数不需要参数。

从选择器声明中删除:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow"), name: UIKeyboardWillShowNotification, object: nil)

或更改您的功能

func keyboardWillShow(notification: NSNotification) {
    self.view.frame.origin.y += CGFloat(keyboardHeight)
}

并对keyboardWillHide执行相同操作。

答案 1 :(得分:0)

请注意,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的方式。你可以使用这个优秀的lib https://github.com/hackiftekhar/IQKeyboardManager来处理键盘上升。使用起来非常简单。