Swift 2 addObserver for specific textField with the object parameter

喜夏-厌秋 提交于 2019-12-05 16:57:54

First, am I understanding the addObserver method correctly (especially the object parameter)

Yes, you've got it. Specifying nil means that you'll get the notification regardless of which object sent it; providing a pointer to an object means that you're observing the notification from that specific object.

second, why is it not registering notifications from self.bottomTextField

You're observing the wrong notification. UITextField never sends UIKeyboardWillShowNotification -- that's a notification that comes from the window. If you specify nil for the object parameter, then you get the notification from any object that sends it, including the window. But when you specified the text field as the object parameter, you didn't get any notification at all because text fields don't send that notification. You should instead observe UITextFieldTextDidBeginEditingNotification and UITextFieldTextDidEndEditingNotification, which are the notifications that UITextField sends.

Because on your code, the self.bottomTextField did not trigger the notification, but the keyboard, when u pass the sender to the object param, only notifications sent by this sender are delivered to the observer, if u use nil mean it will be receive by all source

To fix your problem, u have to convert your textfield point to get the textfield or use textfield delegate such as textFieldShouldBeginEditing and textFieldShouldEndEditing which have textfield param with it

The category to get the current responder textfield:

#import "UIResponder+FirstResponder.h"

static __weak id currentFirstResponder;

@implementation UIResponder (FirstResponder)

+(id)currentFirstResponder {
    currentFirstResponder = nil;
    [[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) to:nil from:nil forEvent:nil];
    return currentFirstResponder;
}

-(void)findFirstResponder:(id)sender {
    currentFirstResponder = self;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!