SwiftUI 3.Button介绍和使用
SwiftUI 的 Button
是用于触发用户操作的核心交互组件。以下是 Button
的详细介绍和使用示例:
一、基础用法
1. 创建简单按钮
Button("点击我") {print("按钮被点击了")
}
2. 自定义按钮内容
Button {// 点击动作
} label: {Text("保存").font(.headline).padding().background(.blue).foregroundColor(.white).cornerRadius(10)
}
3. 结合图标和文字
Button {// 分享操作
} label: {HStack {Image(systemName: "square.and.arrow.up")Text("分享")}
}
二、高级功能
1. 按钮样式(ButtonStyle)
// 使用系统预设样式
Button("提交") { /* ... */ }.buttonStyle(.borderedProminent) // iOS 15+ 样式// 自定义样式
struct CapsuleButtonStyle: ButtonStyle {func makeBody(configuration: Configuration) -> some View {configuration.label.padding().background(configuration.isPressed ? .gray : .blue).foregroundColor(.white).clipShape(Capsule())}
}Button("自定义样式") { /* ... */ }.buttonStyle(CapsuleButtonStyle())
2. 禁用按钮
@State private var isDisabled = falseButton("禁用按钮") { /* ... */ }.disabled(isDisabled) // 禁用状态.opacity(isDisabled ? 0.5 : 1.0)
3. 长按菜单(iOS 15+)
Button("更多操作", role: .destructive) { /* ... */ }.contextMenu {Button("复制") { /* ... */ }Button("删除", role: .destructive) { /* ... */ }}
三、自定义交互
1. 点击动画
Button("点击缩放") {// 点击动作
}
.scaleEffect(isPressed ? 0.9 : 1.0) // 通过 @GestureState 控制
2. 状态绑定
@State private var isOn = falseButton {isOn.toggle()
} label: {Image(systemName: isOn ? "poweron" : "poweroff")
}
四、与其他组件结合
1. 在列表中使用
List {Section {Button("编辑个人资料") { /* ... */ }Button("退出登录", role: .destructive) { /* ... */ }}
}
2. 导航按钮
NavigationStack {NavigationLink {DetailView()} label: {Button("查看详情") { /* ... */ }}
}
五、常见问题
-
按钮无响应:
- 检查是否被其他视图覆盖(使用
Spacer()
确保布局正确) - 确保父视图未设置
allowsHitTesting(false)
- 检查是否被其他视图覆盖(使用
-
样式不生效:
- 修饰符顺序可能影响效果(先定义样式再添加布局)
-
动态内容更新:
@State private var count = 0 Button("点击计数: \(count)") { count += 1 }
六、完整示例
struct ContentView: View {@State private var isEnabled = true@State private var counter = 0var body: some View {VStack(spacing: 20) {// 带图标的按钮Button {counter += 1} label: {Label("增加", systemImage: "plus.circle").font(.title3).padding().background(.orange.gradient.opacity(0.2)).cornerRadius(10)}// 切换禁用状态Toggle("启用按钮", isOn: $isEnabled)// 动态样式按钮Button("计数器: \(counter)") {counter -= 1}.disabled(!isEnabled).buttonStyle(.borderedProminent).tint(isEnabled ? .green : .gray)}.padding()}
}
通过合理组合这些功能,可以实现从简单操作到复杂交互的各种按钮需求。