How to change font of UIButton with Swift

前端 未结 16 1271
故里飘歌
故里飘歌 2020-12-12 11:51

I am trying to change the font of a UIButton using Swift...

myButton.font = UIFont(name: \"...\", 10)

However .font is depreca

相关标签:
16条回答
  • 2020-12-12 12:32

    From the documentation:

    The font used to display text on the button. (Deprecated in iOS 3.0. Use the font property of the titleLabel instead.)

    0 讨论(0)
  • 2020-12-12 12:35

    Use titleLabel instead. The font property is deprecated in iOS 3.0. It also does not work in Objective-C. titleLabel is label used for showing title on UIButton.

    myButton.titleLabel?.font =  UIFont(name: YourfontName, size: 20)
    

    However, while setting title text you should only use setTitle:forControlState:. Do not use titleLabel to set any text for title directly.

    0 讨论(0)
  • 2020-12-12 12:36

    If you need to change only size (Swift 4.0):

    button.titleLabel?.font = button.titleLabel?.font.withSize(12)
    
    0 讨论(0)
  • 2020-12-12 12:38

    If you're having font size issues (your font isn't responding to size changes)...

    @codester has the right code:

    myButton.titleLabel!.font =  UIFont(name: YourfontName, size: 20)
    

    However, my font size wasn't changing. It turns out that I asking for a font that didn't exist ("HelveticaNeue-Regular"). It wasn't causing a crash, but seemed to be just ignoring that font statement because of it. Once I changed the font to something that does exist, changes to "size: x" did render.

    0 讨论(0)
提交回复
热议问题