SwiftUI基础之Button

136 阅读1分钟

1 如何使用Button

1.1 纯文字按钮

Button("123") {
    print("按下按钮")
}
.background(.yellow)

2 图文按钮

2.1 带有系统图片的图文按钮
Button.init("测试", systemImage: "square.and.arrow.up") {
    print("按下按钮")
}

展示如下:

截屏2023-10-19 18.51.01.png

2.2 自定义图片的图文按钮
Button("测试", image: ImageResource.init(name: "coverImage", bundle: Bundle.main)) {
    print("按下按钮")
}

展示如下:

截屏2023-10-19 19.01.02.png

3 更加自定义的方式构造Button

Button.init(action: {
    print("按下按钮")
}, label: {
    Text("测试")
}).background(.yellow)

label参数是闭包返回View,所以可以利用这个方法设置上图下文的图文按钮

Button.init(action: {
    print("按下按钮")
}, label: {
    VStack {
        Image(systemName: "square.and.arrow.up")
        Text("测试")
    }
}).background(.yellow)

展示如下:

截屏2023-10-19 19.10.56.png

4 使用PrimitiveButtonStyleConfiguration创建按钮

enum StylesSet {
    struct CustomButton: PrimitiveButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            Button(configuration)
                  .background(.yellow)
        }
    }
}

struct ContentView: View {
    var body: some View {
        Button(action: {
            print("按下按钮")
        }, label: {
            Text("测试按钮").foregroundColor(.white)
        }).buttonStyle(StylesSet.CustomButton())
    }
}

展示如下:

截屏2023-10-19 19.46.32.png

5 iOS15更新

在iOS15更新了一系列方法,都是新增了role参数,role是ButtonRole类型有下面两个值:

  • destructive
  • cancel destructive是系统红色,cancel是系统蓝色
Button.init("测试", role: .destructive) {
    print("按下按钮")
}

展示如下:

截屏2023-10-19 19.15.44.png

6 常用方法

disabled 设置不可点击
Button("123") {
    print("按下按钮")
}
.background(.yellow)
.disabled(true)
bold 字体加粗
Button("123") {
    print("按下按钮")
}
.background(.yellow)
.bold()
font 设置字体
Button("123") {
    print("按下按钮")
}
.background(.yellow)
.font(.title)
foregroundStyle 文字和系统图片颜色
Button("123") {
    print("按下按钮")
}
.background(.yellow)
.foregroundStyle(.red)