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

Gav*_*sen 12 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

tur*_*ted 15

Font has weight as one of it's properties, so instead of applying fontWeight to the text you can apply the weight to the font and then add the font to the text, like this:

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)
        }
} 
Run Code Online (Sandbox Code Playgroud)

  • +1:我认为这是最好的解决方案,因为您不会尝试通过避免使用 ViewModifier 来对抗 SwiftUI 架构。此外,您还可以将它与任何“动态大小”字体一起使用,例如我在我的应用程序中使用了`Font.largeTitle.weight(.semibold)`。 (2认同)
  • 是否有某种方法要求“内容”符合文本协议或类似协议?我正在考虑泛型类型。 (2认同)

LuL*_*aGa 9

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

extension Text {

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

要使用它,只需调用:

Text("Whatever").h1()
Run Code Online (Sandbox Code Playgroud)


Ash*_*lls 5

像\xe2\x80\xa6 这样的东西怎么样?

\n\n
extension Text {\n\n    enum Style {\n        case h1, h2 // etc\n    }\n\n    func style(_ style: Style) -> Text {\n        switch style {\n        case .h1:\n            return \n             foregroundColor(.black)\n            .font(.system(size: 24))\n            .fontWeight(.semibold)\n        case .h2:\n            return \n             foregroundColor(.black)\n            .font(.system(size: 20))\n            .fontWeight(.medium)\n        }\n    }\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后你可以使用调用

\n\n
Text("Hello, World!").style(.h1) // etc\n
Run Code Online (Sandbox Code Playgroud)\n