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

时间:2019-08-31 22:02:58

标签: 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)
    }
}

3 个答案:

答案 0 :(得分:3)

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

extension Text {

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

要使用它,只需调用:

Text("Whatever").h1()

答案 1 :(得分:1)

字体具有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)
        }
} 

答案 2 :(得分:0)

怎么样……

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