我正在尝试创建 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)
您可以通过在 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)
像\xe2\x80\xa6 这样的东西怎么样?
\n\nextension 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\nRun Code Online (Sandbox Code Playgroud)\n\n然后你可以使用调用
\n\nText("Hello, World!").style(.h1) // etc\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3294 次 |
| 最近记录: |