简体   繁体   中英

How do I change the font of a UILabel in swift without changing the font size?

I have programatically created a label which I have set the adjustsToFitWidth to true. Now I want to change its font, but I can't do that without making the font size of the label constant. Does anybody know how I could change only the font and not the font size of a UILabel in swift?

Why not get the font size, and specify a new font with this value ?

let fontSize = self.label.font.pointSize;
self.label.font = UIFont(name: "HelveticaNeue", size: fontSize)

You can do it like this:

label.font = UIFont(name: "Arial", size: label.font.pointSize)

This will use the same font size, "Arial" can be whatever family you want to choose.

An improved answer.

UILabel Subclassing: Add an empty swift file and name it. eg.EZLabel. Add the following code.

import Foundation
import UIKit

class EZLabel: UILabel {

    override func awakeFromNib() {
        super.awakeFromNib()
        changeFontName()
    }

    func changeFontName()
    {
        self.font = UIFont(name: "Roboto", size: self.font.pointSize)
    }
}

The advantage is that you don't need to change each UILabel's font in the whole project if needed.

extension UILabel {
    override open func awakeFromNib() {
        super.awakeFromNib()
        changeFontName()
    }

    func changeFontName()
    {
        self.font = UIFont(name: "YOUR_FONT_NAME", size: self.font.pointSize)
    }
}

/* Do this also for buttons and any uiviews */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM