Search code examples
swiftxcodefontsnsattributedstringxcode11

Having trouble applying the "Rockwell" font to an attributed string


I'm trying to create an attribute that I can apply as needed to a few different button titles. I need the attributes to apply size 35 font of type "Rockwell", of my own custom color called "specialYellow", with an underline. I'm having trouble when trying to get it to apply the "Rockwell" font because it is not a UIFont color apparently.

let underlineAttribute:[NSAttributedString.Key: Any] = [
    .font: UIFont.systemFont(ofSize: 35),
    .foregroundColor: ColorManager.specialYellow,
    .underlineStyle: NSUnderlineStyle.single.rawValue]

I believe I need to change "UIFont.systemFont" to something else like "UIFont.Rockwell" but swift doesn't accept this.


Solution

  • You just need to use UIFont(name: size:) initializer

    init?(name fontName: String, size fontSize: CGFloat)
    

    but you need to pass the font weight along with its name:

    let rockwellRegular = UIFont(name: "Rockwell-Regular", size: 35)
    

    in your case:

    let underlineAttribute: [NSAttributedString.Key: Any] = [
        .font: UIFont(name: "Rockwell-Regular", size: 35),
        .foregroundColor: ColorManager.specialYellow,
        .underlineStyle: NSUnderlineStyle.single.rawValue]