为什么我不能在 iOS11 中设置搜索栏的文本颜色?

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

我在早期版本中使用它来获取我的搜索栏中的文本字段...

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

在iOS11,还是可以的,我可以改text、font,甚至tintcolor,就是不会设置textcolor,请教我

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

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

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;

在swift中,你可以试试:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.red]

我在这里找到这个答案:

也试过直接将txfSearchFielddefaultTextAttributes设置为[NSAttributedStringKey.foregroundColor.rawValue: UIColor.red]不会改变文字颜色。但是改backgroundColor就可以了,不知道为什么。

终于找到方法了,这样写:

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

托尼的回答很有效。这是这些行的 Swift 5 版本:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange])