Search code examples
iosobjective-cdelegatesuitextfielduinavigationitem

UITextField cannot resign its keyboard when inside UINavigationItem


So I am implementing a custom navigation item in my view controller via the method like this

-(UINavigationItem*)navigationItem{
    item = [[SearchNavigationItem alloc] init];
    item.delegate = self;
    return item;
}

The SearchNavigationItem will set itself up, add a UITextField and so on.

The field.delegate will have the item as the delegate.

So the issue I have is that when I try to grab the text of the field, it is nil. But when the "textfield changed" is called, I can access the field via the argument (textFieldDidChange:UITextField*) and it has the text.

Another issue, like the title, was that when I did [field resignFirstResponder] nothing happened.


Solution

  • Okay so I already have the answer, and I am writing this question because I could personally not find any help while fixing it.


    So the issue is that navigationItem can be called multiple times and this kept creating new bars.

    So the solution became, simply, this:

    -(UINavigationItem*)navigationItem{
        // Apparently it should be treated as a 'singleton' which I think it says
        // kind of in the documentation. This comment is just to reinforce that
        // it burned me to init it each time this method is called. Which is can
        // be multiple times and also outside of the class itself (like when nav'ing)
        if(item == nil){
            item = [[SearchNavigationItem alloc] init];
            item.delegate = self;
        }
        return item;
    }
    

    Hope this helps someone else.