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
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)
加上上面的答案.如果要保持搜索栏样式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)
Swift 5 和 iOS 13
searchBar.searchTextField.backgroundColor = .white
Run Code Online (Sandbox Code Playgroud)
您可以直接更改文本字段背景的颜色。
| 归档时间: |
|
| 查看次数: |
12468 次 |
| 最近记录: |