开发者

Adjust UIButton font size to width

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?


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 :)


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.


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.


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 
        }
    }
}

Adjust UIButton font size to width


in latest swift this seems to work for me

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


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.


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.


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
            }
        }
    }


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)
        }
    }
}


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

Adjust UIButton font size to width


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜