Ahmad
Ahmad

Reputation: 13406

Change font size to fit text inside button entirely?

I'm trying to fit the letter '6' inside a UIButton so that the font automatically scales down when the program is run on a small screen device, such that the letter 6 is inside from all sides.

I found several other threads offering solutions to the same problem but for some reason they don't work for me. A few threads I found were:

I have tried the following two code sequences but none gets the job done:

What should I do ?

1:

self.sixButton.titleLabel!.numberOfLines = 0;
self.sixButton.titleLabel!.adjustsFontSizeToFitWidth = true;
self.sixButton.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping

2:

self.sixButton.titleLabel!.minimumScaleFactor = 0.5;
self.sixButton.titleLabel!.numberOfLines = 0;
self.sixButton.titleLabel!.adjustsFontSizeToFitWidth = true;

3: Same as above but with self.sixButton.titleLabel!.numberOfLines = 1;.

I'm using Swift 2.2 with Xcode 7.3.1.

A picture of the button at design time:

enter image description here

A picture of the button at run time:

enter image description here

Upvotes: 2

Views: 722

Answers (2)

Westside
Westside

Reputation: 685

My solution to this would be to have a label and an invisible button that work together. The invisible button sits on top of the label. The behaviour of text in a label is more flexible and predictable than that of a button in my experience. This probably isn't the cleverest or slickest solution, but it works great and it's painless to implement. You just need to ensure that your constraints keep the button and label aligned.

Upvotes: 0

matt
matt

Reputation: 534885

What I would do is measure the size of the "6" in successively smaller font sizes until we get to a size that fits in the desired bounds, and use that size.

Upvotes: 1

Related Questions