如何以编程方式更改标签的字体?

时间:2014-12-15 21:53:48

标签: ios swift watchkit

我可以在WatchKit扩展程序的Storyboard中设置后,以编程方式更改标签的字体吗?

2 个答案:

答案 0 :(得分:10)

您可以通过setAttributedText上的WKInterfaceLabel进行操作。在属性文本字典上设置字体时,请使用NSFontAttributeName作为密钥。

答案 1 :(得分:2)

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

}