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

ton*_*ony 3 iphone objective-c ios ios11

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

UITextField *searchField = [self.navigationItem.searchController.searchBar valueForKey:@"_searchField"];
Run Code Online (Sandbox Code Playgroud)

在iOS11中,它仍然可以使用,我可以更改文本(字体,甚至colortcolor),但是我无法设置文本颜色,请教我。

UISearchController *mySearchController = [[UISearchController alloc] initWithSearchResultsController:nil];
mySearchController.searchResultsUpdater = self;
self.navigationItem.searchController = mySearchController;
Run Code Online (Sandbox Code Playgroud)

// 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;
Run Code Online (Sandbox Code Playgroud)

ton*_*ony 7

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

[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setDefaultTextAttributes:@{NSForegroundColorAttributeName: [UIColor greenColor]}];
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: [UIColor orangeColor]}]];
Run Code Online (Sandbox Code Playgroud)


yzy*_*hao 5

您可以快速尝试:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.red]
Run Code Online (Sandbox Code Playgroud)

我在这里找到答案:iOS 11在导航栏中自定义搜索栏

也试过直接设置defaultTextAttributestxfSearchField,以[NSAttributedStringKey.foregroundColor.rawValue: UIColor.red]不会改变文本的颜色。但是改变backgroundColor会奏效,不知道为什么。