搜索栏,如何改变文本颜色?

4

这是我的搜索栏外观

我的搜索栏默认是灰色文字,但我想把它改为白色文字。我不知道如何使用Swift更改范围栏文本颜色,并且无法从Storyboard中实现。我找到的最接近的方法是

searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)

但是不幸的是,这也行不通。有什么想法吗?
5个回答

12

在 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

非常感谢 x100。我永远想不到这个。 - 36 By Design
这是公共API吗?换句话说,当提交时,苹果会接受那段代码吗? - Gobe
“public API”是什么意思?苹果不关心你的代码。 - Dejan Skledar
这也可以让您更改字体 :) - Michael

3
// My preferred way of accessing searchField

if let searchTextField = self.searchBar.valueForKey("searchField") as? UITextField {

  searchTextField.textAlignment = NSTextAlignment.Left

}

这是一个私有接口吗? - Carl Smith
不是的... 搜索文本字段在搜索栏上没有正式暴露,但可以通过KVO访问。 - Damo

3

Swift 3

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white

0
在我的情况下,适用于Swift 3.0:
(mySearchBar.value(forKey:“searchField”) as?UITextField)?.textColor = UIColor.white

0
searchBar.searchTextField.textColor = .white

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接