0

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

            }

        }
Giulio Colleluori
  • 1,261
  • 2
  • 10
  • 16

4 Answers4

1

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.

Community
  • 1
  • 1
brimstone
  • 3,370
  • 3
  • 28
  • 49
1

Try this:

let textFieldInSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInSearchBar?.font = UIFont.systemFont(ofSize: 10)
Florian Ldt
  • 1,125
  • 3
  • 13
  • 31
1

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.

Super_Simon
  • 1,250
  • 8
  • 25
iOS Lifee
  • 2,091
  • 23
  • 32
-1
if #available(iOS 9.0, *) {
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.blueColor()
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).font = UIFont.systemFontOfSize(17)
}
hichris123
  • 10,145
  • 15
  • 56
  • 70
Alex Kosyakov
  • 2,095
  • 1
  • 17
  • 25