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

时间:2017-10-27 04:21:17

标签: ios objective-c iphone ios11

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

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

在iOS11中,它仍然有效,我可以更改文字,字体,甚至是tintcolor,但我不能设置文字颜色,请教我。

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;

3 个答案:

答案 0 :(得分:3)

在swift中,您可以尝试:

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

我在这里找到了这个答案:iOS 11 customise search bar in navigation bar

同时尝试defaultTextAttributestxfSearchField的直接设置[NSAttributedStringKey.foregroundColor.rawValue: UIColor.red]不会更改文字颜色。但是改变backgroundColor会起作用,不知道为什么。

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

托尼的答案很好。这是这些行的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])