如何使NSNotificationCenter仅在选择某个UITextField时运行

时间:2015-05-19 00:59:16

标签: ios iphone swift cocoa nsnotificationcenter

我正在使用NSNotificationCenter在显示键盘时向上移动主视图框。

但是,我只想在选择一个UITextField时才能使用它。

这是我到目前为止所做的:

func getKeyboardHeight(notification: NSNotification) -> CGFloat {
    let userInfo = notification.userInfo

    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue

    return keyboardSize.CGRectValue().height

}

func keyboardWillShow(notification: NSNotification) {
    self.view.frame.origin.y -= getKeyboardHeight(notification)
}

func keyboardWillHide(notification: NSNotification) {
    self.view.frame.origin.y += getKeyboardHeight(notification)
}

func subscribeToKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}

func unsubscribeToKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
}

func subscribeToKeyboardHide() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

func unsubscribeToKeyboardHide() {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
  

在ViewWillAppear()

self.subscribeToKeyboardNotifications()
self.subscribeToKeyboardHide()
  

在ViewWillDisappear()

self.unsubscribeToKeyboardNotifications()
self.unsubscribeToKeyboardHide()

当我只选择一个特定的UITextField时,如何使视图向上移动?

2 个答案:

答案 0 :(得分:5)

试试这个

if yourTextfield.isEditing{}

或者这个

if yourTextfield.isFirstResponder{}

要检查这是你的文本域

答案 1 :(得分:1)

您可以创建以下扩展程序

 extension UIView {
    /**
    Finds the first responder

    :returns: the first responder, or nil if nothing found.
    */
    private func findFirstResponder() -> UIView? {
        if isFirstResponder() { return self }
        else {
            for view in subviews as! [UIView] {
                if let responder = view.findFirstResponder() {
                    return responder
                }
            }
            return nil
        }
    }
}

然后在keyboardWillShow

中调用它
let textField = UIApplication.sharedApplication().keyWindow?.findFirstResponder() as? UITextField

您现在可以使用当前活动的textField。