iosobjective-cuitextfielduisearchbaruitextinput

selectedTextRange return nil in UISearchbar iOS


I have aUISearchBar, I get theUITextfield in it and then I want to set selected Text range but it's always return nil. This is my code:

UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
[searchField becomeFirstResponder]; // focus to this searchfield

And I fill in the text:

self.searchBar.text = @"This is text";

And checked if theUITextField text is filled in and it is. Still, all the methods regardingUITextPosition andUITextRange return nil:

UITextRange *selectedRange = [searchField selectedTextRange]; //selectedRange = nil
UITextPosition *newPosition = [searchField positionFromPosition:selectedRange.start offset:addressToComplete.street.length]; //newPosition = nil
UITextRange *newRange = [searchField textRangeFromPosition:newPosition toPosition:newPosition]; //newRange = nil

My code is wrong something?


Solution

  • Have you tried Logging UITextField *searchField? its nil from the looks of it.. i think your code is supposed to be..

    (UITextField *)[self.searchBar valueForKey:@"_searchField"]

    ([after trying your code] OooOoKayyy.. it works.. hahaha..) By the way this is how i get UITextField inside searchBar..

    for (id object in [[[self.searchBar subviews] objectAtIndex:0] subviews])
    {
        if ([object isKindOfClass:[UITextField class]])
        {
            UITextField *searchField = (UITextField *)object;
            break;
        }
    }
    

    First i tried what you have which is:

    UITextField *searchField = (UITextField *)[searchBar valueForKey:@"_searchField"];
    searchBar.text = @"This is text";
    // and logging your searchField.text here.. returns nil/empty.. 
    

    and i tried rearranging it like this...

     searchBar.text = @"This is text";
     UITextField *searchField = (UITextField *)[searchBar valueForKey:@"_searchField"];
     NSLog(@"searchFields.text :%@", searchField.text);
    

    again i tried your code under -(void)viewDidLoad but no good, yeah it is always nil as you said.. now it looks like this..

    - (void)viewDidLayoutSubviews
    {
        [super viewDidLayoutSubviews];
        searchBar.text = @"This is text"; // not important
    
        UITextField *searchField = [searchBar valueForKey:@"_searchField"];
        [searchField becomeFirstResponder];
    
         UITextRange *selectedRange = [searchField selectedTextRange]; //selectedRange = not nil anymore
    
         NSLog(@"searchField.text :%@ -> selectedRange :%@\n\n" , searchField.text, selectedRange);
    }
    //i've also tried it inside uibutton's event and i worked .. >.< 
    

    i programmatically selectedTextRange(for example purposes) and probably it something to do with the xibs autolayout or something (weird i dont experience it) but there it is, try it.. :)

    i hope i've helped you..

    Happy coding.. Cheers!