SwiftUI—Button按钮控件的使用
2020-07-10 本文已影响0人
anny_4243
原文链接:https://github.com/fzhlee/SwiftUI-Guide#10Button
相当于UIKit中的UIButton控件,用于实现接收用户的点击事件。
示例代码:
VStack{
Button("First button") { //添加一个按钮,指定标题文字为 First button
print("---First button action.") //当按钮被点击时,在控制台输出相应的日志(在实时预览模式无法查看按钮的日志输出,运行以后才可以)
}
Button(action: {
print("---Second button action.") //使用另一种初始化方法,添加一个按钮控件,首先设置按钮的点击事件,当按钮被点击时,在控制台输出指定的信息
}) {
Text("Second button") //然后指定一个文本视图,作为按钮的文字标签
}
Button(action: {
print("---Third button action.")
}) {
Image(systemName: "clock")
Text("Third button") //添加一个图像视图和文本视图作为按钮的标签内容
}
.foregroundColor(Color.white) //按钮文字颜色
.background(Color.orange) //按钮背景颜色
//按钮的内边距默认为0
//padding for button : the tap area is wrong
Button(action: {
print("---padding for button.")
}){
Text("Default padding")
}
.padding(30) //内边距为30
.background(Color.yellow)
//padding for label : the tap area is correct!
Button(action: {
print("---padding for label.")
}){
Text("Default padding")
.padding()
.background(Color.yellow)
} //另一种设置方法,显示效果与上一种相同
Button(action: {
print("---Button with image.")
}){
HStack { //可以组合多个子视图,并使子视图沿着水平方向等距排列
Image(systemName: "star")
Text("Button with image")
}
.padding() //水平排列视图的内边距
.background(Color.yellow) //水平排列视图的背景颜色
}
}
