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,121
  • 2
  • 9
  • 15

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,314
  • 3
  • 28
  • 48
1

Try this:

let textFieldInSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInSearchBar?.font = UIFont.systemFont(ofSize: 10)
Florian Ldt
  • 759
  • 1
  • 11
  • 26
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,123
  • 6
  • 24
iOS Lifee
  • 1,881
  • 22
  • 28
-1
if #available(iOS 9.0, *) {
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.blueColor()
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).font = UIFont.systemFontOfSize(17)
}
hichris123
  • 9,955
  • 15
  • 53
  • 68
Alex Kosyakov
  • 1,986
  • 1
  • 15
  • 25