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

Chh*_*oro 3 textcolor uisearchbar swift

我谷歌几个小时如何更改我的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];
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误.

你能告诉我如何更改UISearchBar字体大小和颜色?

请帮忙!!!

Vja*_*del 11

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

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

// SearchBar placeholder
let textFieldInsideUISearchBarLabel = textFieldInsideUISearchBar!.value(forKey: "placeholderLabel") as? UILabel
textFieldInsideUISearchBarLabel?.textColor = UIColor.red
Run Code Online (Sandbox Code Playgroud)


Sof*_*ner 7

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

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


Tua*_*yen 6

在 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
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用:

searchBar.textField?.font = UIFont.systemFont(ofSize: 12)
Run Code Online (Sandbox Code Playgroud)