重用Modifier是,加速SwiftUI代码实现的常用方法之一。下面以常用的文本标签为例,介绍样式重用的定义与使用过程
1. 定义标签样式
struct TagText:ViewModifier{
func body(content: Content) -> some View {
return content
.font(.system(size: 10))
.padding(2)
.overlay(Rectangle().stroke(Theme().theme.themeColor, lineWidth: 0.1))
.foregroundColor(Theme().theme.themeColor)
.background(Theme().theme.themeColor.opacity(0.06))
}
}
2. 扩展View,用起来更方便
extension View {
func tagText() -> some View {
modifier(TagText())
}
}
3. 在SwiftUI视图中应用
Text("\(item.progress ?? "创意阶段")")
.tagText()
实现效果如下: