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 ?

SunnySydeUp
  • 6,680
  • 4
  • 28
  • 32
nine9
  • 147
  • 1
  • 2
  • 8
  • you just want to change font and size or attributed string ? – Moin Shirazi Mar 31 '16 at 04:23
  • attributed string is better – nine9 Mar 31 '16 at 05:06
  • `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](http://stackoverflow.com/questions/11839044/how-do-i-apply-uiappearance-proxy-properties-to-uilabel), which is essentially the exactly the same question, but using Objective-C – David Berry Mar 31 '16 at 05:32

4 Answers4

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.

Durul Dalkanat
  • 7,266
  • 4
  • 35
  • 36
Oleg Sherman
  • 2,772
  • 1
  • 21
  • 20
  • 3
    this has been invaluable. Here's how I applied it. http://stackoverflow.com/questions/41138367/how-do-i-rewrite-a-uilabel-after-it-is-added-to-a-subview – Greg Dec 15 '16 at 11:02
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)
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • 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. – nine9 Mar 31 '16 at 05:04
2

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

for Swift 3 :

label.font = label.font.withSize(20)
Kiran Jadhav
  • 3,209
  • 26
  • 29
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()])
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38