Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the font of a label programmatically?

Can I change the label's font programmatically after I set it up in the Storyboard of my WatchKit extension?

like image 220
Balazs Nemeth Avatar asked Dec 15 '14 21:12

Balazs Nemeth


Video Answer


2 Answers

You can do it via setAttributedText on WKInterfaceLabel. Use NSFontAttributeName for the key when you set the font on the attributed text dictionary.

like image 171
Stephen Johnson Avatar answered Nov 13 '22 01:11

Stephen Johnson


import WatchKit
import Foundation


class InterfaceController: WKInterfaceController {
    @IBOutlet weak var label1: WKInterfaceLabel!
    @IBOutlet weak var label2: WKInterfaceLabel!
    @IBOutlet weak var label3: WKInterfaceLabel!

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)

        // Configure interface objects here.
        let headlineFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
        let footnoteFont = UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote)
        let text1 = NSMutableAttributedString(string: "Tangerine Bold")
        text1.addAttribute(NSFontAttributeName, value: headlineFont, range: NSMakeRange(0, 3))
        text1.addAttribute(NSFontAttributeName, value: footnoteFont, range: NSMakeRange(3, 3))
        label1.setAttributedText(text1)

        let regularFont = UIFont.systemFontOfSize(24)
        let heavyFont = UIFont.systemFontOfSize(24, weight: UIFontWeightHeavy)
        let text2 = NSMutableAttributedString(string: "Tangerine Regular")
        text2.addAttribute(NSFontAttributeName, value: regularFont, range: NSMakeRange(0, 3))
        text2.addAttribute(NSFontAttributeName, value: heavyFont, range: NSMakeRange(3, 3))
        label2.setAttributedText(text2)

        let text3 = NSMutableAttributedString(string: "Tangerine Bold (Code)")
        if let tangerineBoldFont = UIFont(name: "Tangerine-Bold", size: 20) {
            text3.addAttribute(NSFontAttributeName, value: tangerineBoldFont, range: NSMakeRange(0, 21))
        }
        label3.setAttributedText(text3)

    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

}
like image 27
Durul Dalkanat Avatar answered Nov 13 '22 02:11

Durul Dalkanat