How to change UISearchBar Font Size & Color?

寵の児 提交于 2019-12-05 20:48:46

To change text and placeholder searchbar:

// 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

Here's how you can change the font and text color on latest Swift:

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

You can use the Appearance proxies to style the UISearchBar text and placeholder:

Change placeholder:

let placeholderAppearance = UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self])
placeholderAppearance.font = UIFont(name: "Baskerville", size: 14)
placeholderAppearance.textColor = .red

Change search text:

let searchTextAppearance = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
searchTextAppearance.font = UIFont(name: "Baskerville", size: 14)
searchTextAppearance.textColor = .green
Mukul Sharma
searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!