ios 如何使用 Swift 默认 UILabel 字体和大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36323751/
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-31 08:48:23  来源:igfitidea点击:

How to default UILabel Font and Size using Swift

iosswiftuilabeluiappearance

提问by nine9

I find UISegmentedControlchange font and size like this :

我发现UISegmentedControl像这样更改字体和大小:

UISegmentedControl.appearance().setTitleTextAttributes(myFontAttribute as [NSObject : AnyObject] , forState: .Normal)

UISegmentedControl.appearance().setTitleTextAttributes(myFontAttribute as [NSObject : AnyObject] , forState: .Normal)

but UILabel have no this method

但是 UILabel 没有这个方法

I want to do like

我想做

UILabel.appearance().setAttributed(myFontAttribute)

UILabel.appearance().setAttributed(myFontAttribute)

I don't want to change UILabel font in StoryBoard

我不想在 StoryBoard 中更改 UILabel 字体

I want to using program to do this (because my app is done, but only font should change to bigger and other font)

我想使用程序来执行此操作(因为我的应用程序已完成,但只有字体应更改为更大和其他字体)

What should I do ?

我该怎么办 ?

回答by Oleg Sherman

First you need to add extension to UILabel :

首先,您需要向 UILabel 添加扩展名:

extension UILabel{
    var defaultFont: UIFont? {
        get { return self.font }
        set { self.font = newValue }
    }
}

Second use appearance to set it:

第二种使用外观来设置它:

    UILabel.appearance().defaultFont = UIFont.systemFont(ofSize: 25)

Hope it helps.

希望能帮助到你。

回答by Rashwan L

You can change the label font programmatically like this

您可以像这样以编程方式更改标签字体

label.font = UIFont(name: label.font.fontName, size: 14)

Change font size only with bold

仅使用粗体更改字体大小

label.font = UIFont.boldSystemFontOfSize(18)

Change font size only

仅更改字体大小

label.font = label.font.fontWithSize(14)

回答by Kiran jadhav

if you want to change the size of font, used below lines of code :

如果要更改字体大小,请使用以下代码行:

for Swift 3 :

对于 Swift 3 :

label.font = label.font.withSize(20)

回答by Moin Shirazi

You can use this simple code in swift

您可以快速使用这个简单的代码

myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])