UIButton label text is clipped

I have a UIButton built into Interface Builder that has a default label. In Xcode, I change the label text like this:

myButton.titleLabel.text = @"this is the new label"; 

However, when the text is updated, the new line is cut to the same size as the original line, and looks like this:

 this...label 

Does anyone know why this is happening?

+38
iphone cocoa-touch uibutton
Jan 01 '10 at 23:39
source share
6 answers

You must use setTitle: forState: to change the UIButton header. If you change the name yourself, the button does not indicate the need to change the size of the label - you will have to do something like this:

 myButton.titleLabel.text = @"this is the new label"; [myButton setNeedsLayout]; 

but I'm not even sure that this will work in all cases. Methods like setTitle:forState: are provided in such a way that you can provide headers for several states without having to manually update the button, and so that the button knows that it should be laid out with a new header.

+65
Jan 03 2018-11-11T00:
source share

Try using the setTitle method of the button (instead of setting the title directly on the shortcut). This should result in a resizing of the title label.

Goal C:

 [myButton setTitle:@"This is the text" forState:UIControlStateNormal]; 

Or in Swift:

 myButton.setTitle("This is the text", for: .normal) 
+28
Apr 3 '13 at
source share

An alternative solution is to allow UIBabton UIBabton to compress the font size, as UILabels does:

 button.titlelabel.minimumFontSize = 8.0; // or some more adequate size self.buttonWithLongTitle.titleLabel.adjustsFontSizeToFitWidth = YES; 
+21
Jun 01 2018-12-12T00:
source share

Call sizeToFit on your button. This will resize the button to fit the text.

+8
Jan 02 2018-10-10T00:
source share

If this does not work, you can always determine the size of the line and adjust the width of the button border. In this case, you are sure that it will do.

 // Calculate the size CGSize buttonSize = [@"My text.." sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:someSize lineBreakMode:UILineBreakModeWordWrap]; // Do whatever you want with the "buttonSize", you can for example adjust your button frame width 
+1
Jan 04 2018-11-11T00:
source share

Solution in Swift 4.2

 yourButton.titleLabel?.minimumScaleFactor = 0.5 //set whatever you want here to scale yourButton.titleLabel?.adjustsFontSizeToFitWidth = true 

Solution for Objective C

 [yourButton.titleLabel setMinimumScaleFactor:0.5]; [yourButton.titleLabel setAdjustsFontSizeToFitWidth:YES]; 
0
Apr 19 '19 at 8:57
source share



All Articles