简体   繁体   English

将 UIButton 字体大小调整为宽度

[英]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).问题是当文本中的字符串不长时,它显示得很好(1-2位)。 However, when it's quite long (3++ digit), all I can see is a red button, with no text inside.但是,当它很长(3++ 位)时,我只能看到一个红色按钮,里面没有文字。 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: EliBud 的答案不适用于 iOS 8。我找到了适用于 iOS 8 的解决方案。下面是 swift 代码:

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.您可以使用 label?.lineBreakMode,因为我发现结果因不同的中断模式而异。

in latest swift this seems to work for me在最新的 swift 这似乎对我有用

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

iOS 10.3 solution based on the other answers here: iOS 10.3 解决方案基于此处的其他答案:

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

Nobody mentioned baselineAdjustment yet;还没有人提到baselineAdjustment I needed it because the button label becomes vertically misaligned after adjustsFontSizeToFitWidth takes effect.我需要它,因为在adjustsFontSizeToFitWidth生效后,按钮 label 变得垂直未对齐。 Apple's baselineAdjustment documentation:苹果的baselineAdjustment文档:

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.如果adjustsFontSizeToFitWidth属性设置为true ,则在需要调整字体大小的情况下,此属性控制文本基线的行为。 The default value of this property is alignBaselines .此属性的默认值为alignBaselines This property is effective only when the numberOfLines property is set to 1 .此属性仅在numberOfLines属性设置为1时有效。


FWIW, I could never get the label perfectly aligned. FWIW,我永远无法让 label 完全对齐。

Swift 4 extension Swift 4扩展

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

在此处输入图像描述

adjustsFontSizeToFitWidth wasn't working for me until I set a width constraint on my button in Interface Builder. adjustsFontSizeToFitWidth对我不起作用,直到我在 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:基于 Nik Kov 的回答:

import UIKit


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

Xamarin.iOS solution Xamarin.iOS解决方案

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.我最终设置了字体大小以确保在系统调整大小以适应之前字体是“大”的。

In iOS 13.1 with Swift 5, I had to provide contentEdgeInsets also to adjust the paddings.在 iOS 13.1 和 Swift 5 中,我还必须提供contentEdgeInsets来调整填充。

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

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. Boolean 值指示 object 是否在设备的内容大小类别更改时自动更新其字体。

if none of the other answers helps, make sure you set the default storyboard style value and then adjustsFontSizeToFitWidth should work.如果其他答案都没有帮助,请确保设置默认的 storyboard 样式值,然后adjustsFontSizeToFitWidth应该可以工作。

按钮道具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM