ios 将 UIButton 字体大小调整为宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6178545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:09:32  来源:igfitidea点击:

Adjust UIButton font size to width

iosobjective-c

提问by adit

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?

问题是当文本中的字符串不长时,它显示正常(1-2 位)。但是,当它很长(3++ 位)时,我只能看到一个红色按钮,里面没有文字。我该如何调整?

I don't think that:

我不认为:

[button.titleLabel setAdjustsFontSizeToFitWidth:YES];

does the job, right?

工作,对吗?

回答by elibud

Try this:

尝试这个:

button.titleLabel.numberOfLines = 1;
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.lineBreakMode = NSLineBreakByClipping; //<-- MAGIC LINE

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

我不知道为什么这会奏效,但确实如此:)

回答by joakim

button.titleLabel.adjustsFontSizeToFitWidth = YES;

should do the work on its own if you are using Auto-Layoutand 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.

其他选项(最小比例因子、行数等)仍可用于根据您的需要进一步自定义,但不是必需的。

回答by Alexander Belyavskiy

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 ,因为我发现结果因不同的中断模式而异。

回答by tolbard

in latest swift this seems to work for me

在最新的 swift 中,这似乎对我有用

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

回答by Pup

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 baselineAdjustmentyet; I needed it because the button label becomes vertically misaligned after adjustsFontSizeToFitWidthtakes effect. Apple's baselineAdjustmentdocumentation:

还没有人提到baselineAdjustment;我需要它,因为按钮标签在adjustsFontSizeToFitWidth生效后会垂直错位。苹果的baselineAdjustment文档:

If the adjustsFontSizeToFitWidthproperty 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 numberOfLinesproperty is set to 1.

如果该adjustsFontSizeToFitWidth属性设置为true,则在需要调整字体大小的情况下,此属性控制文本基线的行为。此属性的默认值为alignBaselines。此属性仅在numberOfLines设置为时有效1



FWIW, I could never get the label perfectly aligned.

FWIW,我永远无法完全对齐标签。

回答by kraftydevil

adjustsFontSizeToFitWidthwasn'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.

设置约束可以防止按钮变大,因此没有意识到它必须缩小文本。

回答by Nik Kov

Swift 4 extension

斯威夫特 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 
        }
    }
}

enter image description here

在此处输入图片说明

回答by Zaporozhchenko Oleksandr

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

回答by ben

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.

我最终设置了字体大小以确保在系统调整大小以适合之前字体是“大”的。

回答by Vinayak

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.

一个布尔值,指示当设备的内容大小类别更改时对象是否自动更新其字体。