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

How to make NSNotificationCenter only run when a certain UITextField is selected

我正在使用 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)
}

In ViewWillAppear()

self.subscribeToKeyboardNotifications()
self.subscribeToKeyboardHide()

In ViewWillDisappear()

self.unsubscribeToKeyboardNotifications()
self.unsubscribeToKeyboardHide()

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

您可以创建以下扩展

 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。

试试这个

if yourTextfield.isEditing{}

或者这个

if yourTextfield.isFirstResponder{}

检查这是不是您的文本字段