Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change UISearchBar Font Size & Color?

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

like image 611
Chhorn Soro Avatar asked Feb 26 '18 07:02

Chhorn Soro


3 Answers

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 labelInsideUISearchBar = textFieldInsideUISearchBar!.value(forKey: "placeholderLabel") as? UILabel
labelInsideUISearchBar?.textColor = UIColor.red
like image 118
Vjardel Avatar answered Nov 12 '22 16:11

Vjardel


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
like image 8
SoftDesigner Avatar answered Nov 12 '22 16:11

SoftDesigner


In the iOS 13 or newest, the UISearchBar has a property called searchTextField. But earlier, we can not use this property.

So, we can extend for 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
    }
}

And use:

searchBar.textField?.font = UIFont.systemFont(ofSize: 12)
like image 7
Tuan Nguyen Avatar answered Nov 12 '22 16:11

Tuan Nguyen