更改UISearchBar的textField的背景

我现在正在为此苦苦挣扎。 已经遍地search,但提供的解决scheme只适用于Objective-C。 其中包含

UITextField *txt = [_searchBar valueForKey:@"_searchField"];

虽然有些人可能会说这是受保护的API,而苹果可能会拒绝这样的代码的应用程序。

所以,现在我已经尝试了很多方法来解决这个问题,而且根本不能工作。 我的代码是这样的:

 searchBar = UISearchBar(frame: CGRectMake(0, 0, 320.0, 30.0)) searchBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth searchBar.searchBarStyle = UISearchBarStyle.Minimal searchBar.layer.cornerRadius = 15 searchBar.delegate = self searchBar.backgroundColor = UIColor.whiteColor() if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1{ // Load resources for iOS 6.1 or earlier searchBar.placeholder = "Search"; } else { // The following "hack" (if we can call that) breaks the UI for different size devices. // Load resources for iOS 7 or later searchBar.placeholder = "Search "; } 

这给了我奇怪的结果: 在这里输入图像说明

虽然我想要的只是在UISearchBar内的文本字段有一个白色的背景,而且SearchBar本身有一个angular落,例如15。

我怎样才能做到这一点?

非常感谢

您必须访问UISearchBar中的UITextField。 你可以通过使用valueForKey("searchField")

 var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField textFieldInsideSearchBar?.textColor = yourcolor textFieldInsideSearchBar?.backgroundColor = backgroundColor ... 

在那里你可以改变任何参数像UITextField的textColor或backgroundColor

添加到上面的答案。 如果要保持search栏样式UISearchBarStyleMinimal并更改UISearchBar的textField的背景,请将textField的borderStyle设置为UITextBorderStyleNone

目标C:

 self.searchBar.searchBarStyle = UISearchBarStyleMinimal; UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"]; txfSearchField.borderStyle = UITextBorderStyleNone; txfSearchField.backgroundColor = yourColor; 

在Swift 3:

 if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField { txfSearchField.borderStyle = .none txfSearchField.backgroundColor = .lightGray }