简体   繁体   中英

How to set font weight of a custom font in Swift

As far as my research found, we need to provide the different font weight and style of a custom font to be able to use bold or italic. Here is an example

import Foundation
import UIKit

private let familyName = "Montserrat"

enum AppFont: String {
    case light = "Light"
    case regular = "Regular"
    case bold = "Bold"

    func size(_ size: CGFloat) -> UIFont {
        if let font = UIFont(name: fullFontName, size: size + 1.0) {
            return font
        }
        fatalError("Font '\(fullFontName)' does not exist.")
    }
    fileprivate var fullFontName: String {
        return rawValue.isEmpty ? familyName : familyName + "-" + rawValue
    }
}

However, is it possible to increase the font weight ( same effect as <strong> tag in css ) in Swift without providing the bold version of that custom font?

In other framework we can achieve this like this:

Text(
  'Home',
  style: TextStyle(
    fontWeight: FontWeight.w300, // light
    fontStyle: FontStyle.italic, // italic
  ),
);

If that is not possible in swift, how do we mimic the bold effect with other method?

"Fake bold" is done by increasing the stroke width. It doesn't generally look good, but it can work.

SwiftUI's Text does not support arbitrary text attributes, and I'm not aware of any way to pass stroke width to it. I believe you'd have to wrap up a UILabel and an NSAttributedString. With that, however, you pass a negative strokeWidth to indicate that you want the lines to be thicker and filled in. (Positive stroke widths create "outlined" text.)

let string = NSAttributedString(string: "Hello World", attributes: [.strokeWidth: -10])
label.attributedText = string

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