How to change font of UIButton with Swift

前端 未结 16 1272
故里飘歌
故里飘歌 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:21

    You don't need to force unwrap the titleLabel to set it.

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

    Since you're not using the titleLabel here, you can just optionally use it and if it's nil it will just be a no-op.

    I'll also add as other people are saying, the font property is deprecated, and make sure to use setTitle:forControlState: when setting the title text.

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

    In Swift 5, you can utilize dot notation for a bit quicker syntax:

    myButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)

    Otherwise, you'll use:

    myButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)

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

    this work for me, thanks. I want change text size only not change font name.

    var fontSizeButtonBig:Int = 30
    

    btnMenu9.titleLabel?.font = .systemFont(ofSize: CGFloat(fontSizeButtonBig))

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

    For Swift 3.0:

    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
    

    where "boldSystemFont" and "16" can be replaced with your custom font and size.

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

    This way doesn't work now:

     btn.titleLabel?.font = UIFont(name: "Helvetica", size:12)
    

    This works:

     btn.titleLabel?.font = UIFont.init(name: "Helvetica", size:12)
    
    0 讨论(0)
  • 2020-12-12 12:30

    Dot-notation is awesome (swift 4.2)

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