我已经制作了一个在整个应用程序中使用的按钮样式,但我找不到用文本完成此操作的方法,因此我最终不得不每次都手动添加 .font 内容。我想知道是否有一种方法可以设置它,以便我可以采用一致的方式来设置文本样式。这是我用来设置按钮样式的代码。
struct mainPageButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.frame(width: 200, height: 60, alignment: .center)
.overlay(RoundedRectangle(cornerRadius: 25)
.stroke(Color(colorManager.secondaryGreen), lineWidth: 8)
)
.padding(.all, 20)
}
}
Run Code Online (Sandbox Code Playgroud)
All*_*ian 10
没有...Style类似的协议,Text但你有很多其他选择(也许Prestyled不是最好的名字,但你明白了):
单独视图
struct PrestyledText: View {
private let text: String
init(_ text: String) {
self.text = text
}
var body: some View {
Text(text)
.font(.body)
.foregroundColor(.blue)
}
}
Run Code Online (Sandbox Code Playgroud)
修饰符
struct Prestyled: ViewModifier {
func body(content: Content) -> some View {
content
.font(.body)
.foregroundColor(.blue)
}
}
Run Code Online (Sandbox Code Playgroud)
扩大
extension View {
var prestyled: some View {
self.font(.body).foregroundColor(.blue)
}
}
// or
extension View {
var prestyled: some View {
self.modifier(Prestyled())
}
}
Run Code Online (Sandbox Code Playgroud)
范围继承
VStack {
Text("Hello")
Text("There")
}
.font(.body)
.foregroundColor(.blue)
Run Code Online (Sandbox Code Playgroud)
以及使用所有这些的示例:
struct ContentView: View {
var body: some View {
VStack {
PrestyledText("Hello")
Text("Hello").prestyled
VStack {
Text("Hello")
Text("There")
}
.font(.body)
.foregroundColor(.blue)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2866 次 |
| 最近记录: |