I am trying to change the font of a button on my view controller in my code because it is not working in the storyboard. For some reason, I keep trying but am unable to change the font of my button. Here's what my code looks like. The font name I chose is "Print Clearly" and I already set it up correctly so that it works on text fields, but am having trouble with buttons.
@IBOutlet weak var songSuggestButton: UIButton!
var theFont : UIFont = UIFont(name: "Print Clearly", size: 12)!
override func viewDidLoad() {
super.viewDidLoad()
songSuggestButton.titleLabel?.font = theFont
print(songSuggestButton.titleLabel?.font.fontDescriptor())
}
The print tells me the font is Print Clearly and size 12, but still shows up as the default font when I run my app.
Update: The second answer actually worked for me.
> Try this:
@IBOutlet weak var songSuggestButton: UIButton!
override func viewDidAppear() {
super.viewDidAppear(false)
songSuggestButton.titleLabel?.font = UIFont(name: "Print Clearly", size: 12)!
print(songSuggestButton.titleLabel?.font.fontDescriptor())
}
Strange how my custom fonts for buttons only work when initiated through this code. I also wanted to have different sizes of the font for my different view sizes, is there a way about doing this? Thanks.
You can follow these instructions:
Now you can use the following code:
songSuggestButton.titleLabel?.font = UIFont (name: "Print Clearly", size: 12)
UPDATE:
You can put this code both in viewDidLoad
or viewDidAppear
,
UIKit
is not thread safe and should only be updated from the main thread.
So to make sure you will update your UI on the main thread you can do:
dispatch_async(dispatch_get_main_queue()) {
songSuggestButton.titleLabel?.font = theFont
songSuggestButton.setNeedsDisplay()
}
To answer to your last question you must know that label is constrained, and when you change the label size, you change the label frame dimension and so change also his constraints. If you have few view, the best way in iOS is to make different xib's with different label size and load the best xib for that view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With