0

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?

tech_human
  • 6,592
  • 16
  • 65
  • 107
  • Depending on the moment of the life cycle of your object you are making that call on, `self.navigationCopntroller.navigationBar` might == nil. If that is the case, NO is the correct behaviour. – Vincent Bernier Oct 22 '13 at 04:03

1 Answers1

-1

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.

HalR
  • 11,411
  • 5
  • 48
  • 80
  • I modified my code above. I tried adding the textField as the subview to the navigation bar. But its still not working as the first responder. I am using the search bar delegate methods for my code, but I have a code which handles the cursor positioning on the search bar which uses UITextField. I am unit testing that code for which I need UITextField as the first responder to perform some operations. – tech_human Oct 22 '13 at 01:45