Auto change the font size to fit the button in swift

后端 未结 4 1704
青春惊慌失措
青春惊慌失措 2021-02-20 07:47

I have tried this but it didn\'t work, the text is out of the button boundaries.

button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.numberOfL         


        
相关标签:
4条回答
  • 2021-02-20 08:12

    This worked for me:

     button.titleLabel?.font = UIFont(name: "Avenir Next", size: 20)
        button.titleLabel?.adjustsFontSizeToFitWidth = true
        button.titleLabel?.numberOfLines = 1
        button.titleLabel?.minimumScaleFactor = 0.1
        button.clipsToBounds = true
    
    0 讨论(0)
  • 2021-02-20 08:18

    Adjust font size to fit width

    Swift

    self.button.titleLabel?.adjustsFontSizeToFitWidth = true
    

    Objective-C

    [self.button.titleLabel setAdjustsFontSizeToFitWidth:YES];
    
    0 讨论(0)
  • 2021-02-20 08:22

    You can try this:

    1.define the title size based on the current font size of your button

    let nsTitle = NSString(string:"yourButtonTitle")
    let font = button.titleLabel?.font
    let titleSize = nsTitle.sizeWithAttributes([NSFontAttributeName:font])
    

    2.check whether your title fits the button title label :

    if titleSize.width > button.titleLabel?.bounds.width{
    
        //set the appropriate font size
    
    }else{
    
        //set the appropriate font size or do nothing
    }
    
    0 讨论(0)
  • 2021-02-20 08:31

    UIButton font scaling can be very fickle, I've had problems with it in the past. What I did was make the number of lines equal to 1, which worked for me.

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