SwiftUI 修饰符详解大全
下面将按照功能分类详细介绍 SwiftUI 的所有重要修饰符,包括每个修饰符的用法、参数和实际应用。
一、布局修饰符
1. 尺寸和约束
swift
// 1.1 frame - 基本尺寸控制
.frame(width: 100, height: 200) // 固定尺寸
.frame(minWidth: 50, maxWidth: 150) // 最小最大尺寸
.frame(idealWidth: 100, idealHeight: 200) // 理想尺寸
.frame(maxWidth: .infinity) // 无限扩展
.frame(width: nil, height: 100) // 仅限制高度
// 1.2 fixedSize - 使用理想尺寸
.fixedSize() // 水平和垂直都使用理想尺寸
.fixedSize(horizontal: true, vertical: false) // 仅水平固定
// 1.3 layoutPriority - 布局优先级
.layoutPriority(1) // 优先级 0-1000,默认0
.layoutPriority(999) // 高优先级
// 1.4 几何阅读器相关
.coordinateSpace(name: "mySpace") // 定义坐标系
.position(x: 100, y: 200) // 绝对位置
.offset(x: 10, y: 20) // 相对偏移
2. 对齐方式
swift
// 2.1 堆栈对齐
VStack(alignment: .leading) { ... } // VStack水平对齐
HStack(alignment: .top) { ... } // HStack垂直对齐
// 2.2 alignmentGuide - 自定义对齐
.alignmentGuide(.leading) { d in
d[.trailing] // 自定义对齐规则
}
// 2.3 对齐修饰符
.multilineTextAlignment(.center) // 多行文本对齐
3. 间距和边距
swift
// 3.1 padding - 内边距
.padding() // 默认边距
.padding(20) // 统一边距
.padding(.horizontal, 20) // 水平边距
.padding([.top, .bottom], 10) // 上下边距
.padding(.leading, 20).padding(.trailing, 10) // 分别设置
// 3.2 Spacer - 弹性间距
HStack {
Text("左")
Spacer() // 占据所有可用空间
Text("右")
}
// 3.3 Divider - 分割线
Divider() // 水平分割线
Divider().background(Color.red) // 带颜色的分割线
二、样式和外观修饰符
1. 颜色和背景
swift
// 1.1 前景色
.foregroundColor(.blue) // 前景颜色
.foregroundStyle(.blue) // iOS 15+,支持渐变
.foregroundStyle(.linearGradient(colors: [.blue, .purple],
startPoint: .top,
endPoint: .bottom))
// 1.2 背景
.background(Color.blue) // 纯色背景
.background(
LinearGradient(colors: [.blue, .purple],
startPoint: .top,
endPoint: .bottom)
) // 渐变背景
.background(
Image("pattern")
.resizable()
.opacity(0.2)
) // 图片背景
// 1.3 色调和饱和度
.tint(.blue) // 色调(iOS 15+)
.saturation(0.5) // 饱和度 0-1
.hueRotation(.degrees(45)) // 色相旋转
2. 边框和圆角
swift
// 2.1 边框
.border(Color.blue, width: 2) // 简单边框
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, lineWidth: 2)
) // 自定义边框(更灵活)
// 2.2 圆角
.cornerRadius(10) // 圆角
.clipShape(RoundedRectangle(cornerRadius: 10)) // 裁剪形状
.clipShape(Circle()) // 圆形裁剪
// 2.3 阴影
.shadow(color: .gray, radius: 5, x: 0, y: 2) // 阴影
.shadow(color: .black.opacity(0.3),
radius: 10,
x: 0,
y: 5)
3. 透明度和混合
swift
// 3.1 透明度
.opacity(0.5) // 透明度 0-1
.opacity(isHidden ? 0 : 1) // 条件透明度
// 3.2 混合模式
.blendMode(.multiply) // 混合模式
.blendMode(.screen) // 屏幕混合
.blendMode(.overlay) // 叠加混合
// 3.3 模糊
.blur(radius: 10) // 高斯模糊
.blur(radius: 5, opaque: false) // 非不透明模糊
三、文本修饰符
1. 字体样式
swift
// 1.1 字体类型
.font(.largeTitle) // 系统字体
.font(.system(size: 20, weight: .bold)) // 自定义系统字体
.font(.custom("Helvetica", size: 20)) // 自定义字体
.fontWeight(.bold) // 字重
.fontWeight(.light) // 细体
// 1.2 字体样式
.italic() // 斜体
.bold() // 粗体
.underline() // 下划线
.underline(true, color: .red) // 带颜色的下划线
.strikethrough() // 删除线
.strikethrough(true, color: .gray) // 带颜色的删除线
// 1.3 字体宽度和设计
.fontWidth(.condensed) // 字体宽度(iOS 16+)
.fontDesign(.rounded) // 字体设计(iOS 16+)
.fontDesign(.monospaced) // 等宽字体
.fontDesign(.serif) // 衬线字体
2. 文本布局
swift
// 2.1 行限制
.lineLimit(2) // 最多2行
.lineLimit(1...3) // 1-3行范围
.lineLimit(nil) // 无限制
// 2.2 文本截断
.truncationMode(.tail) // 尾部截断
.truncationMode(.middle) // 中间截断
.truncationMode(.head) // 头部截断
// 2.3 间距和缩放
.lineSpacing(10) // 行间距
.kerning(2) // 字符间距
.tracking(2) // 跟踪(字母间距)
.allowsTightening(true) // 允许紧缩
.minimumScaleFactor(0.5) // 最小缩放比例
3. 文本格式化
swift
// 3.1 大小写
.textCase(.uppercase) // 大写
.textCase(.lowercase) // 小写
.textCase(nil) // 保持原样
// 3.2 数字格式
Text(1234.56, format: .number.precision(.fractionLength(2))) // 数字格式化
Text(Date(), format: .dateTime.year().month().day()) // 日期格式化
// 3.3 本地化
.localizedStringKey("hello_key") // 本地化键
四、图像修饰符
1. 图像调整
swift
// 1.1 大小调整
.resizable() // 可调整大小
.resizable(capInsets: EdgeInsets(), resizingMode: .stretch) // 调整模式
.aspectRatio(contentMode: .fit) // 宽高比
.aspectRatio(16/9, contentMode: .fill) // 特定宽高比
// 1.2 图像渲染
.renderingMode(.template) // 模板模式
.renderingMode(.original) // 原始模式
.colorMultiply(.blue) // 颜色混合
.colorInvert() // 颜色反转
// 1.3 图像缩放
.imageScale(.large) // 图像缩放
.imageScale(.small) // 小尺寸
.imageScale(.medium) // 中等尺寸
2. 符号图像(SF Symbols)
swift
// 2.1 SF Symbols 专用修饰符
.symbolRenderingMode(.monochrome) // 单色模式
.symbolRenderingMode(.multicolor) // 多色模式
.symbolRenderingMode(.hierarchical) // 分层模式
.symbolRenderingMode(.palette) // 调色板模式
// 2.2 符号效果
.symbolEffect(.bounce) // 弹跳效果(iOS 17+)
.symbolEffect(.pulse) // 脉冲效果
.symbolEffect(.variableColor.iterative) // 变量颜色
.symbolEffect(.scale) // 缩放效果
// 2.3 符号变体
.symbolVariant(.fill) // 填充变体
.symbolVariant(.circle) // 圆形变体
.symbolVariant(.square) // 方形变体
.symbolVariant(.slash) // 斜线变体
五、交互修饰符
1. 点击和手势
swift
// 1.1 点击手势
.onTapGesture(count: 1) { // 单击
print("点击")
}
.onTapGesture(count: 2) { // 双击
print("双击")
}
// 1.2 长按手势
.onLongPressGesture(minimumDuration: 1, // 长按1秒
maximumDistance: 10) { // 最大移动距离
print("长按")
} onPressingChanged: { isPressing in
print("按压状态: \(isPressing)")
}
// 1.3 高级手势
.gesture(
DragGesture(minimumDistance: 10) // 拖拽手势
.onChanged { value in
print("拖拽中: \(value.translation)")
}
.onEnded { value in
print("拖拽结束")
}
)
// 1.4 多点触控
.simultaneousGesture(TapGesture()) // 同时手势
.highPriorityGesture(TapGesture()) // 高优先级手势
2. 悬停效果
swift
// 2.1 悬停(macOS)
.onHover { isHovered in // 悬停状态
if isHovered {
print("鼠标悬停")
}
}
// 2.2 悬停样式
.hoverEffect(.highlight) // 高亮效果
.hoverEffect(.lift) // 抬起效果
.hoverEffect(.automatic) // 自动效果
3. 焦点和键盘
swift
// 3.1 焦点管理
.focusable() // 可获取焦点
.focused($isFocused) // 焦点绑定
.focused($isFocused, equals: .field1) // 特定焦点
// 3.2 焦点样式
.focusEffectDisabled() // 禁用焦点效果
.defaultFocus($isFocused, true) // 默认焦点
// 3.3 键盘快捷键
.keyboardShortcut("s", modifiers: .command) // 快捷键
.keyboardShortcut(.defaultAction) // 默认动作
.keyboardShortcut(.cancelAction) // 取消动作
六、动画和过渡修饰符
1. 动画修饰符
swift
// 1.1 基本动画
.animation(.easeInOut, value: isActive) // 指定值变化时动画
.animation(.spring(), value: isActive) // 弹簧动画
.animation(.interactiveSpring(), value: isActive) // 交互式弹簧
// 1.2 动画参数
.animation(
.easeInOut(duration: 0.5)
.delay(0.2)
.repeatCount(3, autoreverses: true),
value: isActive
) // 复杂动画
// 1.3 隐式动画
.animation(.default, value: isActive) // 默认动画
.transaction { t in // 事务动画
t.animation = .easeInOut
t.disablesAnimations = false
}
2. 过渡效果
swift
// 2.1 基本过渡
.transition(.opacity) // 淡入淡出
.transition(.scale) // 缩放过渡
.transition(.slide) // 滑动过渡
// 2.2 组合过渡
.transition(.asymmetric(
insertion: .move(edge: .leading), // 进入动画
removal: .move(edge: .trailing) // 退出动画
))
// 2.3 自定义过渡
.transition(.modifier(
active: MyModifier(active: true), // 激活状态
identity: MyModifier(active: false) // 身份状态
))
3. 变换效果
swift
// 3.1 2D变换
.rotationEffect(.degrees(45)) // 旋转
.rotationEffect(.radians(.pi/4)) // 弧度旋转
.scaleEffect(1.5) // 缩放
.scaleEffect(x: 1, y: 2) // 非均匀缩放
// 3.2 3D变换
.rotation3DEffect(
.degrees(45),
axis: (x: 1, y: 0, z: 0) // 绕X轴旋转
)
.transformEffect(CGAffineTransform( // 自定义变换
translationX: 10,
y: 20
))
七、状态和绑定修饰符
1. 状态管理
swift
// 1.1 状态绑定
.onChange(of: value) { newValue in // 值变化监听
print("值变为: \(newValue)")
}
.onChange(of: value, perform: { newValue in
// 处理变化
})
// 1.2 生命周期
.onAppear { // 视图出现
print("视图出现")
}
.onDisappear { // 视图消失
print("视图消失")
}
.task { // 异步任务
await loadData()
}
// 1.3 连续变化
.onContinuousHover { phase in // 连续悬停
switch phase {
case .active: print("悬停开始")
case .ended: print("悬停结束")
}
}
2. 环境变量
swift
// 2.1 环境值
.environment(\.colorScheme, .dark) // 设置环境值
.environmentObject(userData) // 环境对象
// 2.2 获取环境值
@Environment(\.colorScheme) var colorScheme
@Environment(\.locale) var locale
@Environment(\.calendar) var calendar
@Environment(\.timeZone) var timeZone
3. 偏好键
swift
// 3.1 设置偏好值
.preference(key: MyPreferenceKey.self, value: someValue)
// 3.2 读取偏好值
.onPreferenceChange(MyPreferenceKey.self) { newValue in
print("偏好值变化: \(newValue)")
}
// 3.3 背景偏好值
.backgroundPreferenceValue(MyPreferenceKey.self) { value in
// 基于偏好值的背景
}
八、表单和控件修饰符
1. 表单样式
swift
// 1.1 表单分组
.listRowInsets(EdgeInsets()) // 行内边距
.listRowBackground(Color.blue) // 行背景
.listRowSeparator(.hidden) // 隐藏分隔符
.listRowSeparatorTint(.red) // 分隔符颜色
// 1.2 表单样式
.formStyle(.grouped) // 分组样式
.formStyle(.columns) // 列样式
2. 文本输入
swift
// 2.1 键盘类型
.keyboardType(.emailAddress) // 电子邮件键盘
.keyboardType(.numberPad) // 数字键盘
.keyboardType(.decimalPad) // 十进制键盘
// 2.2 文本自动修正
.autocorrectionDisabled() // 禁用自动修正
.autocorrectionDisabled(true) // 条件禁用
// 2.3 文本内容类型
.textContentType(.emailAddress) // 内容类型
.textContentType(.password) // 密码类型
.textContentType(.oneTimeCode) // 验证码类型
// 2.4 文本输入限制
.textFieldStyle(.roundedBorder) // 文本字段样式
.textInputAutocapitalization(.words) // 自动大写
.submitLabel(.done) // 提交按钮标签
3. 按钮样式
swift
// 3.1 按钮样式
.buttonStyle(.bordered) // 带边框
.buttonStyle(.borderedProminent) // 突出边框
.buttonStyle(.borderless) // 无边框
.buttonStyle(.plain) // 纯文本样式
// 3.2 按钮形状
.buttonBorderShape(.capsule) // 胶囊形状
.buttonBorderShape(.roundedRectangle) // 圆角矩形
.buttonBorderShape(.roundedRectangle(radius: 10)) // 自定义圆角
// 3.3 按钮尺寸
.controlSize(.large) // 大尺寸
.controlSize(.regular) // 常规尺寸
.controlSize(.small) // 小尺寸
.controlSize(.mini) // 迷你尺寸
九、列表和表格修饰符
1. 列表修饰符
swift
// 1.1 列表样式
.listStyle(.plain) // 普通样式
.listStyle(.grouped) // 分组样式
.listStyle(.inset) // 内嵌样式
.listStyle(.insetGrouped) // 内嵌分组
.listStyle(.sidebar) // 侧边栏样式
// 1.2 列表行样式
.listRowSeparator(.visible) // 显示分隔符
.listRowSeparatorTint(.blue) // 分隔符颜色
.listRowSeparator(.hidden, edges: .top) // 隐藏顶部边缘分隔符
// 1.3 列表背景
.listRowBackground(
LinearGradient(colors: [.blue, .purple],
startPoint: .leading,
endPoint: .trailing)
) // 渐变背景
// 1.4 滚动指示器
.scrollIndicators(.visible) // 显示滚动指示器
.scrollIndicators(.hidden) // 隐藏滚动指示器
.scrollIndicators(.visible, axes: .vertical) // 仅垂直显示
2. 表格修饰符
swift
// 2.1 表格样式
.tableStyle(.automatic) // 自动样式
.tableStyle(.inset) // 内嵌样式
// 2.2 表格列
.tableColumnWidth(.fixed(100)) // 固定列宽
.tableColumnWidth(.flexible(minimum: 50, maximum: 200)) // 灵活列宽
.tableColumnWidth(.adaptive(minimum: 50)) // 自适应列宽
// 2.3 表格行
.tableRowBackground(Color.gray.opacity(0.1)) // 行背景
.tableRowSeparator(.visible) // 行分隔符
十、导航修饰符
1. 导航栏
swift
// 1.1 导航标题
.navigationTitle("主页") // 大标题
.navigationBarTitle("主页") // 传统标题(iOS 13-14)
.navigationBarTitle("主页", displayMode: .inline) // 内联显示
.navigationBarTitleDisplayMode(.large) // 大标题模式
.navigationBarTitleDisplayMode(.inline) // 内联模式
.navigationBarTitleDisplayMode(.automatic) // 自动模式
// 1.2 导航栏项目
.navigationBarItems(
leading: Button("取消") { }, // 左侧按钮
trailing: Button("保存") { } // 右侧按钮
)
// 1.3 工具栏
.toolbar { // 工具栏
ToolbarItem(placement: .navigationBarTrailing) {
Button("编辑") { }
}
}
.toolbarBackground(.visible, for: .navigationBar) // 工具栏背景
.toolbarColorScheme(.dark, for: .navigationBar) // 工具栏颜色方案
2. 导航视图样式
swift
// 2.1 导航视图样式
.navigationViewStyle(.stack) // 堆栈样式
.navigationViewStyle(.columns) // 列样式(iPad)
// 2.2 导航链接
.navigationDestination(for: String.self) { value in
DetailView(id: value)
} // 导航目标(iOS 16+)
// 2.3 导航栏隐藏
.navigationBarHidden(true) // 隐藏导航栏
.navigationBarBackButtonHidden(true) // 隐藏返回按钮
十一、安全区域和边缘修饰符
1. 安全区域
swift
// 1.1 忽略安全区域
.ignoresSafeArea() // 忽略所有安全区域
.ignoresSafeArea(.all) // 明确忽略所有
.ignoresSafeArea(.container, edges: .top) // 忽略容器顶部安全区
.ignoresSafeArea(.keyboard) // 忽略键盘区域
// 1.2 边缘忽略
.edgesIgnoringSafeArea(.all) // iOS 13方式
.edgesIgnoringSafeArea([.top, .bottom]) // 忽略特定边缘
// 1.3 安全区域插入
.safeAreaInset(edge: .bottom) { // 安全区域内嵌
BottomToolbar()
}
2. 边缘调整
swift
// 2.1 边缘对齐
.alignmentGuide(.top) { d in
d[.bottom] + 20 // 自定义顶部对齐
}
// 2.2 边缘填充
.padding(.safeArea) // 安全区域填充
.padding(.all, .safeArea) // 所有边缘使用安全区域
十二、可访问性修饰符
1. 可访问性标签和提示
swift
// 1.1 可访问性标签
.accessibilityLabel("保存按钮") // 标签
.accessibilityHint("双击以保存更改") // 提示
.accessibilityValue("进度: 50%") // 值
// 1.2 可访问性标识符
.accessibilityIdentifier("saveButton") // 标识符(测试用)
.accessibility(addTraits: .isButton) // 添加特性
.accessibility(removeTraits: .isImage) // 移除特性
.accessibility(hidden: true) // 隐藏(辅助功能不可见)
2. 可访问性动作
swift
// 2.1 自定义动作
.accessibilityAction(.default) { // 默认动作
print("执行默认动作")
}
.accessibilityAction(named: "自定义动作") {
print("执行自定义动作")
}
// 2.2 可访问性调整
.accessibilityAdjustableAction { direction in // 可调整动作
switch direction {
case .increment: incrementValue()
case .decrement: decrementValue()
@unknown default: break
}
}
十三、高级和组合修饰符
1. 视图修改器组合
swift
// 1.1 链式调用
.modifier(MyCustomModifier()) // 自定义修改器
.compositingGroup() // 组合组(提升性能)
.drawingGroup() // 绘图组(GPU加速)
// 1.2 条件修饰符
.if(isActive) { view in // 条件应用修饰符
view.background(Color.red)
}
2. 性能优化修饰符
swift
// 2.1 绘图优化
.drawingGroup() // 合并绘制层
.compositingGroup() // 组合视图组
// 2.2 缓存优化
.cachingBehavior(.byRequest) // 按请求缓存
.cachingBehavior(.duringDecode) // 解码期间缓存
// 2.3 图像缓存
.imageCache(.persistent) // 持久化缓存
.imageCache(.inMemory) // 内存缓存
3. 自定义修饰符示例
swift
// 3.1 创建自定义修饰符
struct CardModifier: ViewModifier {
let cornerRadius: CGFloat
let shadowRadius: CGFloat
func body(content: Content) -> some View {
content
.padding()
.background(Color.white)
.cornerRadius(cornerRadius)
.shadow(radius: shadowRadius)
.padding(.horizontal)
}
}
// 3.2 扩展 View 使用
extension View {
func cardStyle(radius: CGFloat = 10, shadow: CGFloat = 5) -> some View {
modifier(CardModifier(cornerRadius: radius, shadowRadius: shadow))
}
}
// 3.3 使用自定义修饰符
Text("Hello")
.cardStyle(radius: 15, shadow: 10)
十四、平台特定修饰符
1. iOS 专用修饰符
swift
// 1.1 状态栏样式
.statusBar(hidden: true) // 隐藏状态栏
// 1.2 键盘回避
.keyboardAvoiding() // 键盘回避(第三方库常见)
.scrollDismissesKeyboard(.interactively) // 滚动时关闭键盘
// 1.3 页面控制
.pageControlAppearance(.visible) // 页面控制外观
2. macOS 专用修饰符
swift
// 2.1 窗口修饰符
.windowStyle(.titleBar) // 窗口样式
.windowResizability(.contentSize) // 窗口可调整性
// 2.2 工具栏
.toolbarStyle(.automatic) // 工具栏样式
.toolbarStyle(.unified) // 统一工具栏
// 2.3 光标样式
.onHover { inside in
if inside {
NSCursor.pointingHand.push()
} else {
NSCursor.pop()
}
}
3. 跨平台条件修饰符
swift
// 3.1 条件编译
#if os(iOS)
.navigationBarTitle("iOS标题")
#elseif os(macOS)
.navigationTitle("macOS标题")
#endif
// 3.2 平台适配
.onAppear {
#if os(iOS)
// iOS 特定代码
#endif
}
十五、实用技巧和模式
1. 修饰符顺序的重要性
swift
// 顺序影响结果!
Text("Hello")
.padding() // 先加内边距
.background(Color.blue) // 背景只包裹内容和内边距
.padding() // 再加外边距,背景不会扩展
Text("Hello")
.background(Color.blue) // 背景只包裹文本
.padding() // 内边距在背景外
2. 组合常用样式
swift
// 2.1 创建样式组合
extension View {
func primaryButtonStyle() -> some View {
self
.padding(.horizontal, 20)
.padding(.vertical, 12)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
.shadow(radius: 3)
}
func secondaryButtonStyle() -> some View {
self
.padding(.horizontal, 20)
.padding(.vertical, 10)
.background(Color.gray.opacity(0.2))
.foregroundColor(.blue)
.cornerRadius(8)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue, lineWidth: 1)
)
}
}
// 2.2 使用
Button("保存", action: save)
.primaryButtonStyle()
Button("取消", action: cancel)
.secondaryButtonStyle()
3. 调试修饰符
swift
// 3.1 调试边框
.border(Color.red) // 调试边框
.background(Color.green.opacity(0.3)) // 调试背景
// 3.2 调试尺寸
.overlay(
GeometryReader { geo in
Text("\(Int(geo.size.width))x\(Int(geo.size.height))")
.font(.caption)
.foregroundColor(.red)
.position(x: geo.size.width/2, y: 10)
}
)
// 3.3 调试打印
.onAppear {
print("视图出现,当前尺寸: ...")
}
总结
SwiftUI 修饰符系统非常强大,关键要点:
- 修饰符顺序很重要 - 应用顺序影响最终效果
- 链式调用 - 大多数修饰符返回 View,支持链式调用
- 组合使用 - 多个修饰符组合实现复杂效果
- 自定义扩展 - 通过扩展 View 创建自定义修饰符
- 平台差异 - 注意不同平台的修饰符支持情况
掌握这些修饰符后,就可以创建几乎任何想要的界面效果。建议在实践中不断尝试和组合这些修饰符,以加深理解。