Question

In a unit test I am trying to call becomeFirstResponder method on a UITextField, but I am getting NO i.e. its not becoming the first responder.

The code looks as below:

UITextField *textField = [self.controller.searchBar valueForKey: @"_searchField"];
//    textField = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 10.0, 400.0, 44.0)];
[self.navigationController.navigationBar addSubview:textField];

textField.enabled = YES;
STAssertTrue([textField becomeFirstResponder],
             @"TextField should be a first responder.");

Am I missing something here?

Was it helpful?

Solution

You are grabbing the value of the search bar for the textfield:

UITextField *textField = [self.controller.searchBar valueForKey: @"_searchField"];

But then you just ignore that value, and overwrite it with this:

textField = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 10.0, 400.0, 44.0)];

You haven't added this new textField to any view and its just a lone textfield that is allocated and nothing more. It can't be a first responder because its not part of an app.

There are better ways of getting access to the searchbar.

You can change the location of the search items with calls like searchTextPositionAdjustment and searchFieldBackgroundPositionAdjustment. And you can use the UISearchBarDelegate to get information on the text being entered.

How will it become first responder just because you got a reference to it? Perhaps you meant to use isFirstResponder (it is already the first responder) or canBecomeFirstResponder (it can become the first responder).

Otherwise, you need to set an NSNotification on UITextFieldTextDidBeginEditingNotification to get notified when it begins editing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top