我的搜索栏有默认的灰色文字,但我希望它是白色文字。我无法弄清楚如何使用swift来更改范围栏文本颜色,并且您无法从故事板中执行此操作。我发现的最接近的是
searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)
但是这也无济于事。有什么想法吗?
答案 0 :(得分:10)
有点难以访问UISearchbar内的Textfield。
这是它的工作原理:
for subView in self.searchBarOutlet.subviews
{
for secondLevelSubview in subView.subviews
{
if (secondLevelSubview.isKindOfClass(UITextField))
{
if let searchBarTextField:UITextField = secondLevelSubview as? UITextField
{
//set the color here like this:
searchBarTextField.textColor = UIColor.redColor()
break;
}
}
}
}
更短的解决方案:
var textFieldInsideSearchBar = yourSearchbar.valueForKey(“searchField”) as? UITextField
textFieldInsideSearchBar?.textColor = yourcolor
答案 1 :(得分:3)
// My preferred way of accessing searchField
if let searchTextField = self.searchBar.valueForKey("searchField") as? UITextField {
searchTextField.textAlignment = NSTextAlignment.Left
}
答案 2 :(得分:3)
Swift 3
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white
答案 3 :(得分:0)
在我的swift 3.0案例中
(mySearchBar.value(forKey:" searchField")as?UITextField)?. textColor = UIColor.white
答案 4 :(得分:0)
searchBar.searchTextField.textColor = .white