简体   繁体   中英

How to Change Font Style in Swift

I'm trying to figure out how to change the style of a font to "Thin". Does anyone know how to do this?

Here's my best try, but it doesn't work:

m.font = UIFont(name: "Apple SD Gothic Neo", style: "Thin", size: 8.0)

The way I have seen it is AppleSDGothicNeo-Thin , No spaces, and a dash style. So your code would be

m.font = UIFont(name: "AppleSDGothicNeo-Thin", size: 8.0)

Edit:

I have come to understand why you use the font this way.

If you add a custom font to your project, it has a name of "SuperAwesomeFont-Light.ttf". So it makes sense that you just use the file name for the name of the font.

You have trouble with font name.

At first find out proper name of the font and than use it.

Firstly print all names of them. And then use. Code example show all installed fonts of the application.

func printFonts() {
    let fontFamilyNames = UIFont.familyNames()
    for familyName in fontFamilyNames {
        print("------------------------------")
        print("Font Family Name = [\(familyName)]")
        let names = UIFont.fontNamesForFamilyName(familyName)
        print("Font Names = [\(names)]")
    }
}

And after you detect Font you can set this like :

m.font = UIFont(name: "AppleSDGothicNeo-Thin", size: 8.0)

这可能有效:

let font = UIFont(name: "HelveticaNeue-Thin", size: 16.0)!

Put this in playground to get all correct names of the fonts, available (updated for Swift 3.0 up to Swift 5.0 on basis of oleg)

//: Playground - noun: a place where people can play

import UIKit

func printFonts() {
    let fontFamilyNames = UIFont.familyNames
    for familyName in fontFamilyNames {
        print("------------------------------")
        print("Font Family Name = [\(familyName)]")
        let names = UIFont.fontNames(forFamilyName: familyName)
        print("Font Names = [\(names)]")
    }
}

printFonts()

lblDes.font = UIFont(名称:“HelveticaNeue-UltraLight”,大小:14.0)

let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: yourWidth, height: yourHeight))
    myLabel.text = "Your Text"
    myLabel.font = UIFont(name: "Name of your font", size: 18)
    self.view.addSubview(emptyMessageLabel)
    myLabel.translatesAutoresizingMaskIntoConstraints = false
    myLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    myLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

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