Search code examples
iosxcodeuitextfielduisearchbaruisearchdisplaycontroller

Cannot change searchbar text color, but I am able to change background color


I have a searchbar embedded in a navigationbar. I'm able to change background color, but for the life of me cannot change text color. I have the following code in my viewdidload. What is missing to get the text to change?

if(!itemSearchBar)
    {
        itemSearchBar = [[UISearchBar alloc] init];
        [itemSearchBar setFrame:CGRectMake(0, 0, self.view.frame.size.width, 55)];
        itemSearchBar.placeholder = @"What are you looking for?";
        itemSearchBar.delegate = self;

        UITextField *txfSearchField = [itemSearchBar valueForKey:@"_searchField"];
        txfSearchField.backgroundColor = [UIColor colorWithRed:130/255.0 green:58/255.0 blue:23/255.0 alpha:1.0];


    UISearchDisplayController *searchCon = [[UISearchDisplayController alloc]
             initWithSearchBar:itemSearchBar
             contentsController:self ];

    [searchCon setActive:NO animated:YES];
    self.searchDisplayController = searchCon;
    self.searchDisplayController.delegate = self;
    self.searchDisplayController.searchResultsDataSource = self;
    self.searchDisplayController.searchResultsDelegate = self;
    self.searchDisplayController.displaysSearchBarInNavigationBar=YES;

I've read that the following should work but doesn't:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];

I've also tried:

itemSearchBar.tintColor = [UIColor redColor];
txfSearchField.textColor = [UIColor redColor];

Any suggestions???


Solution

  • I think you are looking at the color of placeholder text and not typing anything in the textfield. Otherwise, your code seems correct. The method

    txfSearchField.textColor = [UIColor redColor] 
    

    must work. Type anything in the field and you will see red color.