Adjust UIButton font size to width

IosObjective C

Ios Problem Overview


I have the following code:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, 25, 25);
       
[[button layer] setCornerRadius:5.0f];
[[button layer] setMasksToBounds:YES];
[[button layer] setBackgroundColor:[[UIColor redColor] CGColor]];
[button.titleLabel setFrame:CGRectMake(0,0, 25, 25)];
                
[button setTitle:[NSString stringWithFormat:@"%@", [[topics objectAtIndex:indexPath.row] unread]] forState:UIControlStateNormal];

The issue is that when the string in the text is not long, it shows fine (1-2 digit). However, when it's quite long (3++ digit), all I can see is a red button, with no text inside. How do I adjust this?

I don't think that:

[button.titleLabel setAdjustsFontSizeToFitWidth:YES];

does the job, right?

Ios Solutions


Solution 1 - Ios

Try this:

button.titleLabel?.numberOfLines = 1
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = .byClipping //<-- MAGIC LINE

I'm not sure why this does the trick but it does :)

Solution 2 - Ios

button.titleLabel.adjustsFontSizeToFitWidth = YES;

should do the work on its own if you are using Auto-Layout and have set a constraint on the button's width.

The other options (minimum scale factor, number of lines etc) can still be used to customize further according to your needs, but are not required.

Solution 3 - Ios

The answer from EliBud doesn't work on iOS 8. I found a solution which works on iOS 8. Below is a swift code:

let label = self.button?.titleLabel
label?.minimumScaleFactor = 0.01
label?.adjustsFontSizeToFitWidth = true
label?.font = UIFont.systemFontOfSize(100)

You can play with label?.lineBreakMode as I found that results varies for different break modes.

Solution 4 - Ios

Swift 4 extension

extension UIButton {
    @IBInspectable var adjustFontSizeToWidth: Bool {
        get {
            return self.titleLabel?.adjustsFontSizeToFitWidth
        }
        set {
            self.titleLabel?.numberOfLines = 1
            self.titleLabel?.adjustsFontSizeToFitWidth = newValue;
            self.titleLabel?.lineBreakMode = .byClipping;
            self.titleLabel?.baselineAdjustment = .alignCenters 
        }
    }
}

enter image description here

Solution 5 - Ios

in latest swift this seems to work for me

button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByClipping

Solution 6 - Ios

iOS 10.3 solution based on the other answers here:

	button.titleLabel!.numberOfLines = 1
	button.titleLabel!.adjustsFontSizeToFitWidth = true
	button.titleLabel!.baselineAdjustment = .alignCenters

Nobody mentioned baselineAdjustment yet; I needed it because the button label becomes vertically misaligned after adjustsFontSizeToFitWidth takes effect. Apple's baselineAdjustment documentation:

> If the adjustsFontSizeToFitWidth property is set to true, this > property controls the behavior of the text baselines in situations > where adjustment of the font size is required. The default value of > this property is alignBaselines. This property is effective only when > the numberOfLines property is set to 1.


FWIW, I could never get the label perfectly aligned.

Solution 7 - Ios

adjustsFontSizeToFitWidth wasn't working for me until I set a width constraint on my button in Interface Builder.

Setting the constraint kept the button from growing in size and therefore not realizing it had to shrink the text.

Solution 8 - Ios

based on Nik Kov's answer:

import UIKit


    extension UIButton {
        @IBInspectable var adjustFontSizeToWidth: Bool {
            get {
                return titleLabel!.adjustsFontSizeToFitWidth
            }
            set {
                titleLabel!.adjustsFontSizeToFitWidth = newValue
                titleLabel!.lineBreakMode             = .byClipping
            }
        }
    }

Solution 9 - Ios

In iOS 13.1 with Swift 5, I had to provide contentEdgeInsets also to adjust the paddings.

extension UIButton {
    @IBInspectable var adjustFontSizeToWidth: Bool {
        get {
            return self.titleLabel?.adjustsFontSizeToFitWidth ?? false
        }
        set {
            self.titleLabel?.numberOfLines = 1
            self.titleLabel?.adjustsFontSizeToFitWidth = newValue;
            self.titleLabel?.lineBreakMode = .byClipping;
            self.titleLabel?.baselineAdjustment = .alignCenters
            self.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
    }
}

Solution 10 - Ios

Xamarin.iOS solution

var accountButton = new UIButton();
accountButton.SetTitle("Account", UIControlState.Normal);            
accountButton.TitleLabel.AdjustsFontSizeToFitWidth = true;
accountButton.TitleLabel.Lines = 1;
accountButton.TitleLabel.LineBreakMode = UILineBreakMode.Clip;
accountButton.TitleLabel.Font = accountButton.TitleLabel.Font.WithSize(35);

I ended up setting the font size to ensure the font was "large" before the system adjusts the size to fit.

Solution 11 - Ios

if none of the other answers helps, make sure you set the default storyboard style value and then adjustsFontSizeToFitWidth should work.

buttons props

Solution 12 - Ios

Below solution worked for me:

button.titleLabel?.adjustsFontForContentSizeCategory = true

The developer documentation explains this property as:

> A Boolean value indicating whether the object automatically updates > its font when the device's content size category changes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaditView Question on Stackoverflow
Solution 1 - IoselibudView Answer on Stackoverflow
Solution 2 - IosjoakimView Answer on Stackoverflow
Solution 3 - IosAliaksandr BialiauskiView Answer on Stackoverflow
Solution 4 - IosNike KovView Answer on Stackoverflow
Solution 5 - IostolbardView Answer on Stackoverflow
Solution 6 - IosPupView Answer on Stackoverflow
Solution 7 - IoskraftydevilView Answer on Stackoverflow
Solution 8 - IosZaporozhchenko OleksandrView Answer on Stackoverflow
Solution 9 - IosBharatView Answer on Stackoverflow
Solution 10 - IosbenView Answer on Stackoverflow
Solution 11 - IosKuperView Answer on Stackoverflow
Solution 12 - IosVinayakView Answer on Stackoverflow