Open boycgit opened 4 years ago
本期学习 SwiftUI 基础控件 Button 的使用,内容基本涵盖了 Button 高频的使用场景;通过本节课你将收获:
视频版长度 14 分钟(内涵 5 小节),点击前往 观看视频
以下是文字版
效果预览:
关键代码:
VStack {
Button("第一个按钮"){
print("被点击了")
}.padding(.bottom, 20)
Button(action: {
print("再次被点击")
}){
Text("又一个按钮")
.font(.title)
.foregroundColor(Color.green)
}
}
效果预览:
关键代码:
VStack {
Button(action: {
print("被点击了呃")
}){
Image(systemName: "play.rectangle")
Text("这是 Button");
}
.font(.title)
.padding()
.background(Color.orange)
.foregroundColor(Color.white)
.cornerRadius(50).padding(10)
.overlay(
RoundedRectangle(cornerRadius: 50).stroke(Color.orange, lineWidth: 5)
)
效果预览:
关键代码:
Button(action: {
print("又被点击了呃")
}){
Text("Hi~ 这是另一个 Button");
}
.font(.title)
.padding()
.background(LinearGradient(gradient: Gradient(colors: [Color("LightGreen"), Color("DarkGreen")]), startPoint: .leading, endPoint: .trailing))
.foregroundColor(Color.white)
.cornerRadius(50).padding(10)
}
效果预览:
关键代码:
Button(action: {
print("被点击了呃")
}){
Text("Hi~这是另一个 Button")
}
.font(.title)
.padding()
.frame(minWidth: 0, maxWidth: .infinity)
.background(LinearGradient(gradient: Gradient(colors: [Color("LightGreen"), Color("DarkGreen")]), startPoint: .leading, endPoint: .trailing))
.foregroundColor(Color.white)
.cornerRadius(50)
.padding(.all, 10)
.shadow(color: Color("DarkGreen"), radius: 5)
分别实现 ButtonStyle 协议:
struct GradientButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.title)
.padding()
.frame(minWidth: 0, maxWidth: .infinity)
.background(LinearGradient(gradient: Gradient(colors: [Color("LightGreen"), Color("DarkGreen")]), startPoint: .leading, endPoint: .trailing))
.foregroundColor(Color.white)
.cornerRadius(50)
.padding(.horizontal, 10)
.shadow(color:Color("DarkGreen"), radius: 5)
.scaleEffect(configuration.isPressed ? 0.9 : 1)
}
}
struct BorderButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.title)
.padding()
.background(Color.orange)
.foregroundColor(Color.white)
.cornerRadius(50)
.padding(.all, 10)
.overlay(
RoundedRectangle(cornerRadius: 50).stroke(Color.orange, lineWidth: 5)
)
}
}
分别装饰:
VStack {
Button(action: {
print("被点击了呃")
}){
HStack{
Image(systemName: "play.rectangle")
Text("这是 Button")
}
}.buttonStyle(BorderButtonStyle())
Button(action: {
print("被点击了呃")
}){
Text("Hi~这是另一个 Button")
}.buttonStyle(GradientButtonStyle())
}
效果预览:
struct ContentView: View {
@State var clickedCount: Int = 0;
...
Text("点击次数:\(clickedCount)");
Button(action: {
print("被点击了呃")
self.clickedCount = self.clickedCount + 1;
})
...
}
It’s a very basic UI control that you can find in all apps and has the ability to handle users’ touch, and trigger a certain action