How to default UILabel Font and Size using Swift
Asked Answered
T

4

8

I find UISegmentedControl change font and size like this :

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

but UILabel have no this method

I want to do like

UILabel.appearance().setAttributed(myFontAttribute)

I don't want to change UILabel font in StoryBoard

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 ?

Thistle answered 31/3, 2016 at 3:45 Comment(3)
you just want to change font and size or attributed string ?Ashanti
attributed string is betterThistle
UIAppearance only allows you to set properties that are flagged with UI_APPEARANCE_SELECTOR in the Objective-C header file. Since UILabel has no such properties, it cannot be styled with UIAppearance See also this question, which is essentially the exactly the same question, but using Objective-CDried
G
35

First you need to add extension to 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.

Guarded answered 31/3, 2016 at 4:25 Comment(1)
this has been invaluable. Here's how I applied it. #41138867Assay
B
12

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)
Beep answered 31/3, 2016 at 4:24 Comment(1)
this idea not good for me, because it need IBOutlet ... I don't want to using IBOutlet. Because I have a lot UILable in my app.Thistle
E
2

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

for Swift 3 :

label.font = label.font.withSize(20)
Eupatrid answered 29/7, 2017 at 11:33 Comment(0)
A
0

You can use this simple code in swift

myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])
Ashanti answered 31/3, 2016 at 5:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.