更改UISearchBar的textField背景
我现在正在为此苦苦挣扎。到处搜索,但提供的解决方案只适用于Objective-C。其中包括在更改UISearchBar的textField背景
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里面的文本框有一个白色的背景和搜索栏本身具有的cornerRadius ,说,15.
我该怎么做?
在此先感谢
这么多,你要访问的UITextField的里面的UISearchBar。你可以通过使用 valueForKey("searchField")
var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = yourcolor
textFieldInsideSearchBar?.backgroundColor = backgroundColor
...
那里你可以改变一样的的UITextField
您应该将样式设置为'Prominent'或'Default.'如果您喜欢使用'Minimal','backgroundColor'不起作用。 'searchBar.searchBarStyle = UISearchBarStyle.Prominent // or .Default' – fatihyildizhan 2016-01-04 16:17:31
@fatihyildizhan谢谢这对于不使用最小风格确实非常重要!花了太多的时间在这.... – Altimac 2016-06-17 14:46:07
添加到上面的回答文字颜色或任何的backgroundColor参数。 如果你想保留搜索栏样式UISearchBarStyleMinimal和改变的UISearchBar的文本框的背景下,文本框的的borderStyle设置为UITextBorderStyleNone
目标C:
self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
txfSearchField.borderStyle = UITextBorderStyleNone;
txfSearchField.backgroundColor = yourColor;
在斯威夫特3:
if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
txfSearchField.borderStyle = .none
txfSearchField.backgroundColor = .lightGray
}
的UITextField * searchField = [SearchBar valueForKey:@“_ searchField”]; searchField.textColor = [UIColor whiteColor]; 我已经在我的应用程序和应用程序中使用此代码,它已经在App Store中可用。 – Bhoomi 2015-04-04 05:42:55