SwiftUI视图修饰方法

基础外观修饰

常用的视图外观修饰方法。

  • Name
    字体修饰
    Type
    font
    Description
    • font(): 设置字体样式
    • foregroundColor(): 设置前景色
    • bold()/italic(): 加粗/斜体
  • Name
    尺寸修饰
    Type
    size
    Description
    • frame(): 设置框架尺寸
    • padding(): 设置内边距
    • offset(): 设置偏移量
  • Name
    背景修饰
    Type
    background
    Description
    • background(): 设置背景
    • overlay(): 设置前景层

基础修饰示例

Text("Hello World")
    .font(.title)
    .foregroundColor(.blue)
    .bold()
    .frame(width: 200, height: 100)
    .padding()
    .background(Color.yellow)
    .cornerRadius(10)

Image(systemName: "star.fill")
    .font(.system(size: 30))
    .foregroundColor(.yellow)
    .offset(x: 10, y: 10)

布局修饰

控制视图布局和对齐方式的修饰符。

  • Name
    对齐方式
    Type
    alignment
    Description
    • alignmentGuide(): 自定义对齐
    • position(): 设置位置
  • Name
    布局控制
    Type
    layout
    Description
    • layoutPriority(): 布局优先级
    • fixedSize(): 固定尺寸
    • aspectRatio(): 宽高比

布局修饰示例

HStack {
    Text("Left")
        .layoutPriority(1)
    Text("Center")
        .layoutPriority(2)
    Text("Right")
}
.frame(maxWidth: .infinity)

Image("photo")
    .aspectRatio(contentMode: .fit)
    .frame(width: 200)

交互修饰

添加用户交互和动画效果。

  • Name
    手势识别
    Type
    gesture
    Description
    • onTapGesture(): 点击手势
    • onLongPressGesture(): 长按
    • gesture(): 自定义手势
  • Name
    动画效果
    Type
    animation
    Description
    • animation(): 添加动画
    • transition(): 转场动画

交互修饰示例

Circle()
    .fill(Color.blue)
    .frame(width: 100, height: 100)
    .onTapGesture {
        withAnimation {
            // 处理点击
        }
    }
    .animation(.spring(), value: isAnimating)

Button("Tap Me") {
    // 动作
}
.transition(.scale)

高级修饰

复杂的组合修饰方法。

  • Name
    环境修饰
    Type
    environment
    Description
    • environment(): 设置环境值
    • environmentObject(): 注入环境对象
  • Name
    条件修饰
    Type
    conditional
    Description
    • mask(): 蒙版效果
    • clipShape(): 裁剪形状
    • matchedGeometryEffect(): 视图匹配

高级修饰示例

Text("Dynamic Text")
    .environment(\.colorScheme, .dark)
    .environment(\.font, .largeTitle)

RoundedRectangle(cornerRadius: 20)
    .fill(Color.blue)
    .frame(width: 200, height: 200)
    .mask(
        Text("Masked")
            .font(.system(size: 50, weight: .bold))
    )

自定义修饰符

创建可重用的自定义修饰符。

  • Name
    定义方法
    Type
    definition
    Description
    • ViewModifier协议
    • 扩展View
  • Name
    使用场景
    Type
    usage
    Description
    • 组合多个修饰符
    • 统一样式定义
    • 代码复用

自定义修饰符示例

struct CardModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(Color.white)
            .cornerRadius(10)
            .shadow(radius: 5)
    }
}

extension View {
    func cardStyle() -> some View {
        modifier(CardModifier())
    }
}

// 使用
Text("Card")
    .cardStyle()

这篇文章对你有用吗?