Search code examples
iosiphoneswiftcocoansnotificationcenter

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


I am using NSNotificationCenter to shift the main view frame up when a keyboard is shown.

However, I only want this to work for when one UITextField is selected.

Here is what I have so far:

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()

How do I make the view shift up when I am only selecting one specific UITextField?


Solution

  • Try this

    if yourTextfield.isEditing{}
    

    Or this

    if yourTextfield.isFirstResponder{}
    

    To check is this is your textfield