更改UISearchBar的textField的背景

Pat*_*sut 17 uisearchbar ios swift

我现在已经挣扎了一段时间.已经到处搜索,但提供的解决方案仅适用于objective-c.其中包括

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

虽然有些人可能会说这是受保护的API,Apple可能会拒绝使用此类代码的应用程序.

所以,现在我已经尝试了很多方法来解决这个问题,但它根本不起作用.我的代码是这样的:

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

这给了我奇怪的结果: 在此输入图像描述

虽然我想要的只是UISearchBar里面的文本字段有白色背景,而SearchBar本身的cornerRadius比如15.

我怎样才能做到这一点?

非常感谢提前

hel*_*tan 29

您必须访问UISearchBar中的UITextField.你可以通过使用来做到这一点valueForKey("searchField")

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

textFieldInsideSearchBar?.textColor = yourcolor
textFieldInsideSearchBar?.backgroundColor = backgroundColor
...
Run Code Online (Sandbox Code Playgroud)

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

  • 你应该将样式设置为`Prominent`或`Default.如果你更喜欢使用`Minimal`,`backgroundColor`不起作用.`searchBar.searchBarStyle = UISearchBarStyle.Prominent //或.Default` (14认同)

Tus*_*reb 16

在Swift 3中:

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


dre*_*psp 9

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

目标C:

self.searchBar.searchBarStyle = UISearchBarStyleMinimal;

UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
    txfSearchField.borderStyle = UITextBorderStyleNone;
    txfSearchField.backgroundColor = yourColor;
Run Code Online (Sandbox Code Playgroud)


vp2*_*698 7

Swift 5 和 iOS 13

searchBar.searchTextField.backgroundColor = .white
Run Code Online (Sandbox Code Playgroud)

您可以直接更改文本字段背景的颜色。

  • 警告:“searchTextField”仅在 iOS 13 之后可用。 (2认同)