How to find out what UITextField caused a UIKeyboardWillShowNotification?

孤者浪人 提交于 2019-12-03 23:28:01

Couldn't get any of the above to work. Had to do it manually:

if ([companyName isFirstResponder]) {
    // ...............
}
else if ([notes isFirstResponder]) {
    //.............
    }
}

You can write a UIView category method to find the first responder.

- (UIView *)firstResponder
{
    if ([self isFirstResponder])
    {
        return self;
    }

    for (UIView *view in self.subviews)
    {
        UIView *firstResponder= [view firstResponder];
        if (firstResponder)
        {
            return firstResponder;
        }
    }

    return nil;
}

Then in your - (void)keyboardWillShow:(NSNotification *)notification method you can use it like this

  UITextField *textField = (UITextField *)[self firstResponder];

That project works great, but when I add an extra UITextField, the custom key gets put into the keyboard for that text field too.

You can set the keyboard type for a UITextField instance, e.g.:

[myTextField setKeyboardType:UIKeyboardTypeDefault];

or:

myTextField.keyboardType = UIKeyboardTypeDefault;

Search the Xcode help on UITextInputTraits Protocol for a list of UIKeyboardType constants.

I have achieved this before by comparing the object with the UI object that I am interested in. Like this:

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