SwiftUI重用:用ViewModifier,定义重复使用的样式

重用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()

实现效果如下:

ViewModifier样式重用
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容