如何更改UISearchBar的字体大小和颜色?

7

我已经谷歌了几个小时关于如何更改我的UISearchBar字体大小和颜色,但是我没有找到任何相关的文档。

这是我在Swift 4上所做的:

 searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: view.frame.width - (menuImage.frame.width + iconImage.frame.width + 55), height: 30))
 searchBar.placeholder = "SEARCH BAR"
 searchBar.tintColor = UIColor.gray
 searchBar.delegate = self
 searchBar.font = [UIFont fontWithName:@"Oswald" size:11];

但是它给我报错了。

请问我该如何改变UISearchBar的字体大小和颜色?

请帮帮我!!!


1
可能是重复的问题,参考如何更改UISearchBar搜索文本颜色? - Suresh Ponnukalai
哦,非常感谢你,它运行得很好。 - Chhorn Soro
5个回答

22

更改搜索栏的文本和占位符:

// SearchBar text
let textFieldInsideUISearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideUISearchBar?.textColor = UIColor.red
textFieldInsideUISearchBar?.font = textFieldInsideUISearchBar?.font?.withSize(12)

// SearchBar placeholder
let labelInsideUISearchBar = textFieldInsideUISearchBar!.value(forKey: "placeholderLabel") as? UILabel
labelInsideUISearchBar?.textColor = UIColor.red

8
以下是如何在最新的Swift中更改字体和文本颜色的方法:

以下是如何在最新的Swift中更改字体和文本颜色的方法:

let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(15), NSAttributedString.Key.foregroundColor: UIColor.gray]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = attributes

7
在iOS 13及以上版本中,UISearchBar具有名为searchTextField的属性。但在早期版本中,我们无法使用此属性。
因此,我们可以对UISearchBar进行扩展:
extension UISearchBar {
    var textField: UITextField? {
        if #available(iOS 13.0, *) {
            return self.searchTextField
        } else {
            // Fallback on earlier versions
            for view in (self.subviews[0]).subviews {
                if let textField = view as? UITextField {
                    return textField
                }
            }
        }
        return nil
    }
}

并使用:

searchBar.textField?.font = UIFont.systemFont(ofSize: 12)

它在iOS 11中无法工作。textField为空。 - HamasN

4
你可以使用外观代理来设置 UISearchBar 的文本和占位符样式:
更改占位符:
let placeholderAppearance = UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self])
placeholderAppearance.font = UIFont(name: "Baskerville", size: 14)
placeholderAppearance.textColor = .red

更改搜索文本:

let searchTextAppearance = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
searchTextAppearance.font = UIFont(name: "Baskerville", size: 14)
searchTextAppearance.textColor = .green

这个可以用于占位符,但不能用于用户输入的文本。 - drewster

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

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