Set UIButton title UILabel font size programmatically

前端 未结 18 2972
灰色年华
灰色年华 2020-12-07 07:16

I need to set the font size of the title UILabel of a UIButton programmatically.

相关标签:
18条回答
  • 2020-12-07 08:02

    To support the Accessibility feature in UIButton

    extension UILabel
    {
       func scaledFont(for font: UIFont) -> UIFont {
            if #available(iOS 11.0, *) {
                return UIFontMetrics.default.scaledFont(for: font)
            } else {
                return font.withSize(scaler * font.pointSize)
            }
        }
        func customFontScaleFactor(font : UIFont) {
            translatesAutoresizingMaskIntoConstraints = false
    
             self.adjustsFontForContentSizeCategory = true
             self.font = FontMetrics.scaledFont(for: font)
        }
    }
    

    You can can button font now.

    UIButton().titleLabel?.customFontScaleFactor(font: UIFont.systemFont(ofSize: 12))
    
    0 讨论(0)
  • 2020-12-07 08:03

    Swift:

    shareButton.titleLabel?.font = UIFont.systemFontOfSize(size)
    

    Unimportant note: deleted by animuson♦ Dec 5 '14 at 16:48
    animuson, I had the same problem now a month after I posted this answer. I was googling and found out this post which wasn't easily copy pastable into a swift project. While I was scrolling saw my deleted answer and copied it. so please don't delete actually useful stuff..

    0 讨论(0)
  • 2020-12-07 08:06
    button.titleLabel.font = <whatever font you want>
    

    For the people wondering why their text isn't showing up, if you do

    button.titleLabel.text = @"something";
    

    It won't show up, you need to do:

    [button setTitle:@"My title" forState:UIControlStateNormal]; //or whatever you want the control state to be
    
    0 讨论(0)
  • 2020-12-07 08:07
    button.titleLabel.font = [UIFont systemFontOfSize:size];
    

    should help

    0 讨论(0)
  • 2020-12-07 08:08

    this may help :

    [objBtn.titleLabel setFont:[UIFont fontWithName:@“fontname” size:fontsize]];
    
    0 讨论(0)
  • 2020-12-07 08:09

    This would be helpful

    button.titleLabel.font = [UIFont fontWithName:@"YOUR FONTNAME" size:12.0f]
    
    0 讨论(0)
提交回复
热议问题