问题
I've google fews hours how to change my UISearchBar font size & color, but I cannot any documents related to it.
This is what I've done so far on 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];
but it gave me an error.
Could you tell me how can I change the UISearchBar font size & color?
Please help!!!
回答1:
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
回答2:
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
回答3:
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
回答4:
searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)
来源:https://stackoverflow.com/questions/48983497/how-to-change-uisearchbar-font-size-color