SwiftUI 控件之Button 按钮初级和高级实用(2020版教程)
Button是一个非常基本的UI控件,您可以在所有应用中找到该控件。如果您以前学习过iOS编程,则SwiftUI中的Button与UIKit中的UIButton非常相似。它更加灵活和可定制。本文将给您介绍一下几个方面的内容:
- 如何创建一个简单的按钮并处理用户的选择
- 如何自定义按钮的背景,填充和字体
- 如何在按钮上添加边框
- 如何同时创建带有图像和文本的按钮
- 如何创建带有渐变背景和阴影的按钮
- 如何创建全角按钮
代码
import SwiftUI
struct ContentView: View {
var body: some View {
Button(action:{
print("touch")
}){
Text("Hello World")
.fontWeight(.bold)
.font(.title)
.padding()
.background(Color.purple)
.cornerRadius(40)
.foregroundColor(.white)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.purple, lineWidth: 5)
)
}
}
}
效果
设置图片按钮
Button(action: {
print("Delete tapped!")
}) {
HStack {
Image(systemName: "trash")
.font(.title)
Text("Delete")
.fontWeight(.semibold)
.font(.title)
}
.padding()
.foregroundColor(.white)
.background(Color.red)
.cornerRadius(40)
}
效果
设置渐变效果
import SwiftUI
struct ContentView: View {
var body: some View {
Button(action: {
print("Delete tapped!")
}) {
HStack {
Image(systemName: "trash")
.font(.title)
Text("Delete")
.fontWeight(.semibold)
.font(.title)
}
.padding()
.foregroundColor(.white)
//.background(Color.red)
.background(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
}
}
}
SwiftUI 自定义颜色集
通过16进制设置颜色
import SwiftUI
struct ContentView: View {
var body: some View {
Button(action: {
print("Delete tapped!")
}) {
HStack {
Image(systemName: "trash")
.font(.title)
Text("Delete")
.fontWeight(.semibold)
.font(.title)
}
.padding()
.foregroundColor(.white)
//.background(Color.red)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
}
}
}
SwiftUI 设置控件铺满整个屏幕
import SwiftUI
struct ContentView: View {
var body: some View {
Button(action: {
print("Delete tapped!")
}) {
HStack {
Image(systemName: "trash")
.font(.title)
Text("Delete")
.fontWeight(.semibold)
.font(.title)
}
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.foregroundColor(.white)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
}
}
}
参考文献
更多SwiftUI教程和代码关注专栏
- 请关注我的专栏 SwiftUI教程与源码