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?

Answers


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. e.g..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 */

Need Your Help

Storing a type in C++

c++ casting types

Is it possible to store a type name as a C++ variable? For example, like this:

How can i fix this warning: CoreSimulator is attempting to unload a stale CoreSimulatorService job

continuous-integration teamcity xcode8 xcodebuild

I have a warning in my build log in teamcity. I've updated Xcode on my CI-Server from 7.3.1 to 8. The step run successfully but I have this: