Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i let text fit to UIButton?

Tags:

problem:

Button size is enough, however when I change title, the title text cannot fit the button width. Any SDK function can solve this problem, or I need to manually code to solve it?

Please refer to following pictures.

design in the nib file. enter image description here

initial show in simulator enter image description here

when I change the title text enter image description here

tried some ways before

  1. _button.titleLabel.adjustsFontSizeToFitWidth = YES;
    the way will change my font size. I cannot accept the way.

  2. [_button setTitleEdgeInsets:UIEdgeInsetsMake(10.0, 10.0, 0.0,0.0)];
    the way change label's position only, not label size.

  3. [_button.titleLabel sizeToFit];
    result is same with picture(3).

  4. [_button sizeToFit];
    title moved to upper left corner, and the title still the same result.

Just confused, my button size is big enough, why title size is so small?

like image 907
CCC Avatar asked Dec 02 '12 04:12

CCC


People also ask

How do I put the image on the right side of the text in a UIButton?

To make an UIButton's image align to the right side of the text, we force content flipping behavior to the one use it right-to-left language. 1 By adding this semanticContentAttribute = . forceRightToLeft , we force UIKit to mirrored our content which push our image to the right side of the text. Here is the result.

How do I turn off highlighting in UIButton?

make your button Type - "Custom" and Uncheck - Highlighted Adjust image and you are done.


2 Answers

Use this.

Objective-c

button.titleLabel.numberOfLines = 1; button.titleLabel.adjustsFontSizeToFitWidth = YES; button.titleLabel.lineBreakMode = NSLineBreakByClipping;  

Swift 2.0

button.titleLabel?.numberOfLines = 0 button.titleLabel?.adjustsFontSizeToFitWidth = true button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping 

NOTE: Swift code courtesy: @Rachel Harvey

Swift 5.0

button.titleLabel?.numberOfLines = 0 button.titleLabel?.adjustsFontSizeToFitWidth = true button.titleLabel?.lineBreakMode = .byWordWrapping 
like image 153
Nilesh Avatar answered Sep 20 '22 18:09

Nilesh


For people who come across with this question:

Try using the setter:

 [self.myButton setTitle:@"Title" forState:UIControlStateNormal];  [self.myButton sizeToFit]; 
like image 44
Jonathan P. Diaz Avatar answered Sep 19 '22 18:09

Jonathan P. Diaz