Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton label text autoshrink with insets

I am using Auto Layout. I have a UIButton with a fixed height and width and a background image (a rounded square). It displays text strings of variable length (between 1 and 30 words, let's say).

I wanted to make the text autoshrink depending on string length, and to have up to 3 lines of text in my button. So I did this:

 [button.titleLabel setMinimumScaleFactor:0.01];
    [button.titleLabel setAdjustsFontSizeToFitWidth: YES];
    [button.titleLabel setNumberOfLines:3];
    [button.titleLabel setTextAlignment:NSTextAlignmentCenter];

I also set the font size to a high value like 50 in the Interface Builder. And I set the line break to "Clip".

The button's text correctly adapts to the number of characters, but it tends to go beyond the frame of the button. It does that for mid-length strings but not for huge strings and I have no idea why. I have tried to add insets to my button but it doesn't do much, only moves the overly-big text around, so I assume the font adjustment is calculated prior to the incorporation of insets.

Below a screenshot. There are 4 of those buttons, contained within the bigger blue view. The red background is the background of the button, the yellow is an image that serves as background.

Screenshot

I uploaded an example project on Google Drive. Use iPhone 6 Plus for simulation.

like image 475
Konrad Avatar asked Sep 30 '22 04:09

Konrad


1 Answers

You should also set your button's titleEdgeInsets property.

For instance:

button.titleEdgeInsets = UIEdgeInsetsMake(2.0, 2.0, 2.0, 2.0);

In your project, it seems that there some layout constraints that are messing with the buttons' title label.

When adding the following constraints, it works.

UILabel *titleLabel = button.titleLabel;
NSDictionary *views = NSDictionaryOfVariableBindings(titleLabel);
[button addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[titleLabel]|"
                                                               options:kNilOptions
                                                               metrics:nil
                                                                 views:views]];

Before using this solution, I suggest you first try to set your layout constraints in a simpler way if possible.

like image 71
Moxy Avatar answered Oct 03 '22 02:10

Moxy