SwiftUI - 自定义 Modifier

317 阅读1分钟

截屏2022-12-09 下午4.37.33.png

1.首先,我们要实现自定义的 Modifier,需要实现 ViewModifier 协议:

struct Vip: ViewModifier {
  let isVip: Bool
  
  func body(content: Content) -> some View {
    HStack {
      content
      if isVip {
        Text("Vip")
          .font(.caption).bold()
          .foregroundColor(.white)
          .padding(3)
          .background(Color.orange)
          .cornerRadius(3)
      } else {
        Button {
          // action
        } label: {
          Text("开通会员")
            .font(.caption)
            .foregroundColor(.white)
            .padding(5)
            .background(Color.blue)
            .clipShape(Capsule())
        }
        .buttonStyle(.borderless)
      }
    }
  }
}

2.然后我们给 View 添加扩展:

extension View {
  func isVip(_ isVip: Bool) -> some View {
    self.modifier(Vip(isVip: isVip))
  }
}

3. 使用

Text("Bruce").isVip(false) 
// 或 
Text("Bruce").isVip(true)