Giulio Colleluori
Giulio Colleluori

Reputation: 1361

How can I programmatically change UIFont of UISearchBar or UITableViewHeader?

I have a UITableView to which I add programmatically a UISearchController as a header. Since I'm adding it programmatically, I can't change the font from the storyboard. I need to change the UISearchBar font to match the font of the rest of the app. I would need to either change the font of a UISearchBar or of the whole tableViewHeader

I saw that there's a similar question with an answer in objective-c, however I'm developing my app in Swift and I tried to convert the answer on the other question to the following code but it still won't work :

let lightFont = UIFont(name: "GothamRounded-Light", size: 15)

        for subview in searchController.searchBar.subviews {
            if subview is UITextField{

                (subview as! UITextField).font = lightFont

            }

        }

Upvotes: 0

Views: 516

Answers (4)

iOS Lifee
iOS Lifee

Reputation: 2201

Add below code in viewDidLoad()

let textFieldInsideUISearchBar = searchBar.value(forKey: "searchField") as? UITextField

let placeholderLabel = textFieldInsideUISearchBar?.value(forKey: "placeholderLabel") as? UILabel

placeholderLabel?.font = UIFont(name: "Avenir Next", size: 13.0) //this will set custom font to placeholder font

textFieldInsideUISearchBar?.font = placeholderLabel?.font //this will set custom font to text font

This will set a custom font to both the placeholder and text in the UISearchBar.

Upvotes: 1

Florian Ldt
Florian Ldt

Reputation: 1235

Try this:

let textFieldInSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInSearchBar?.font = UIFont.systemFont(ofSize: 10)

Upvotes: 1

Alex Kosyakov
Alex Kosyakov

Reputation: 2176

if #available(iOS 9.0, *) {
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.blueColor()
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).font = UIFont.systemFontOfSize(17)
}

Upvotes: -1

brimstone
brimstone

Reputation: 3400

From this question

You'll need to loop through it's subviews to find the UITextField (not accessible by property)

for subview in search.subviews {
   if subview is UITextField {
       (subview as! UITextField).font = UIFont(name: "Arial", size: 24.0)
   }
}

Then you can set it's font.

Upvotes: 1

Related Questions