Adjust font size of text to fit in UIButton

前端 未结 9 995
予麋鹿
予麋鹿 2020-12-08 02:12

I want to make sure the button text fits into a UIButton, while the UIButton has a fixed size.

Of course I can access the titleLabel of the UIButton. In a label I w

相关标签:
9条回答
  • 2020-12-08 02:56

    Updated code for Swift 3.0:

    yourButton.titleLabel?.minimumScaleFactor = 0.5
    yourButton.titleLabel?.numberOfLines = 0
    yourButton.titleLabel?.adjustsFontSizeToFitWidth = true
    
    0 讨论(0)
  • 2020-12-08 02:57
    self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
    self.mybutton.titleLabel.numberOfLines = 0;   <-- Or to desired number of lines
    self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
    

    ... did the trick, after layoutIfNeeded in viewDidLoad As it turns out, all those must be set to actually adjust the font-size, not just making it fit into the frame.

    Update for Swift 3:

    mybutton.titleLabel?.minimumScaleFactor = 0.5
    mybutton.titleLabel?.numberOfLines = 0   <-- Or to desired number of lines
    mybutton.titleLabel?.adjustsFontSizeToFitWidth = true
    
    0 讨论(0)
  • 2020-12-08 02:57

    If you prefer do in storyboard, just click the button, then show attributes inspector, and set the line break to "Word Wrap".

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

    Write this line after your code:

    yourButton.SizeToFitWidth=YES;
    
    0 讨论(0)
  • 2020-12-08 03:06

    try this:

      [myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]];
      textWidth = [text sizeWithFont:[myButton font]].width;
    
    }
    
    0 讨论(0)
  • 2020-12-08 03:07

    to make text horizontally and vertically fit with button bounds :

    1 - set button alignment like image (* VERY IMPORTANT *)

    2 - add this lines of code in your ViewController

    btnTest.setTitle("Test for multi line in button show line in button show Test for multi line in button show line in button show", for: .normal)
    btnTest.titleLabel!.textAlignment = .center
    btnTest.titleLabel!.numberOfLines = 0
    btnTest.titleLabel!.adjustsFontSizeToFitWidth = true
    btnTest.titleLabel!.minimumScaleFactor = 0.5
    // below line to add some inset for text to look better
    // you can delete or change that
    btnTest.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    
    • note that DON'T using btnTest.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping or other BreakMode in your code . for enable multiline in button . just using from above code

    final result :

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