简体   繁体   中英

Set label font with bold and italic

I'm trying to set a specific part of my label to bold and italic with NSMutableAttributedString , but I can only get one or the other. The font that I'm using is Clear Sans. Setting the entire label's font on the storyboard to Bold Italic works fine, but I only need part of it. So I used

for family in UIFont.familyNames() {
    print("\(family)\n\t\(UIFont.fontNamesForFamilyName(family))")
}

to make sure it's there, and I found

Clear Sans
    ["ClearSans", "ClearSans-Bold", "ClearSans-Italic"]

For some reason, it's not in here but it is in the storyboard. So I tried to use this answer , but it crashes, I assume for the same reason that I didn't find ClearSans-BoldItalic , but I don't know why it's not in there.

Finally, I tried to just "stack" the two, like so

let bold = UIFont(name: "ClearSans-Bold", size: 20)
let italic = UIFont(name: "ClearSans-Italic", size: 20)

attributedCaption.addAttribute(NSFontAttributeName, value: bold!, range: (imageContainer.caption as NSString).rangeOfString(matchString))
attributedCaption.addAttribute(NSFontAttributeName, value: italic!, range: (imageContainer.caption as NSString).rangeOfString(matchString))

but all this does is use the last attribute, which is what I had expected it to do.

Is there some other method I can use to do this so that I get both bold and italic to show on the same part of the label?

Edit

I wanted to include my fonts that are in the project, so it's clear that I've already imported them. The second image is the list of fonts on the storyboard. While it's covered up, the family is in fact Clear Sans .

已安装的字体 故事板选项

确保在UIAppFonts (“应用程序提供的字体”)键下的应用程序的Info.plist中还添加了粗体斜体版本。

UIFont.italicSystemFont(ofSize: 15.0)
UIFont.boldSystemFont(ofSize: 15)

if you want to custom font of label like fond system . you can try my solution . it works good for swift 3

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