Search code examples
iosobjective-ciphoneios11

Why can't I set the textcolor of searchbar in iOS11?


I use this in an earlier version to get the textfield in my searchBar...

UITextField *searchField = [self.navigationItem.searchController.searchBar valueForKey:@"_searchField"];

In iOS11, it's still worked, I can change the text、font、even tintcolor,but I just can't set the textcolor, please teach me.

UISearchController *mySearchController = [[UISearchController alloc] initWithSearchResultsController:nil];
mySearchController.searchResultsUpdater = self;
self.navigationItem.searchController = mySearchController;

// mySearchController.hidesNavigationBarDuringPresentation = false; self.navigationItem.hidesSearchBarWhenScrolling = NO;

self.tableView.refreshControl = [[UIRefreshControl alloc] init];
[self.tableView.refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];

self.navigationItem.title = @"xxxx";
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"reload" style:UIBarButtonItemStylePlain target:self action:@selector(refresh)];
self.navigationItem.rightBarButtonItem = item;

UITextField *txfSearchField = [self.navigationItem.searchController.searchBar valueForKey:@"_searchField"];
txfSearchField.tintColor=[UIColor blueColor];

//this code is no use
txfSearchField.textColor=[UIColor yellowColor];

txfSearchField.backgroundColor=[UIColor whiteColor];
UIView *backgroundview= [[txfSearchField subviews]firstObject ];
backgroundview.backgroundColor=[UIColor whiteColor];
backgroundview.layer.cornerRadius = 8;
backgroundview.clipsToBounds = true;

Solution

  • I finally find the way, write like this:

    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setDefaultTextAttributes:@{NSForegroundColorAttributeName: [UIColor greenColor]}];
    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: [UIColor orangeColor]}]];