如何在 SwiftUI 中添加 .fontWeight 作为 ViewModifer 的一部分

How to add .fontWeight as part of a ViewModifer in SwiftUI

我正在尝试创建 ViewModifiers 以在 SwiftUI 中保存我所有的类型样式。当我尝试添加 .fontWeight 修饰符时,出现以下错误: Value of type 'some View' has no member 'fontWeight'

这可能吗?有没有更好的方法来管理我的 SwiftUI 项目中的类型样式?

struct H1: ViewModifier {
    func body(content: Content) -> some View {
        content
            .foregroundColor(Color.black)
            .font(.system(size: 24))
            .fontWeight(.semibold)
    }
}

您可以通过在 Text 的扩展中声明函数来实现此目的,如下所示:

extension Text {

    func h1() -> Text {
        self
            .foregroundColor(Color.black)
            .font(.system(size: 24))
            .fontWeight(.semibold)
    }
}

要使用它,只需调用:

Text("Whatever").h1()

怎么样……

extension Text {

    enum Style {
        case h1, h2 // etc
    }

    func style(_ style: Style) -> Text {
        switch style {
        case .h1:
            return 
             foregroundColor(.black)
            .font(.system(size: 24))
            .fontWeight(.semibold)
        case .h2:
            return 
             foregroundColor(.black)
            .font(.system(size: 20))
            .fontWeight(.medium)
        }
    }
}

然后就可以调用

Text("Hello, World!").style(.h1) // etc

字体有 weight 作为它的属性之一,所以除了将 fontWeight 应用到文本之外,您还可以将粗细应用到字体,然后将字体添加到文本,如下所示:

struct H1: ViewModifier {
    // system font, size 24 and semibold
    let font = Font.system(size: 24).weight(.semibold)

    func body(content: Content) -> some View {
        content
            .foregroundColor(Color.black)
            .font(font)
        }
}