我的搜索栏默认是灰色文字,但我想把它改为白色文字。我不知道如何使用Swift更改范围栏文本颜色,并且无法从Storyboard中实现。我找到的最接近的方法是
searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)
但是不幸的是,这也行不通。有什么想法吗?
在 UISearchbar 中访问 Textfield 有点困难。
以下是访问 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
// My preferred way of accessing searchField
if let searchTextField = self.searchBar.valueForKey("searchField") as? UITextField {
searchTextField.textAlignment = NSTextAlignment.Left
}
Swift 3
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white
searchBar.searchTextField.textColor = .white