「SwiftUI」Button常见样式效果

iOS开发经常会使用Button组件

以下是三种常见的Button UI样式和相应的写法

样式一:背景颜色全部填充

样式如图:
在这里插入图片描述

相应代码:

struct ContentView: View {
    
    var body: some View {
        Button {
            print("open")
        } label: {
            HStack{
                Image("On")
                
                Text("开启")
                    .bold()
                    .font(Font.system(size: 22))
                    .frame(width:300, height: 80, alignment: .center)
            }
        }
        .foregroundColor(Color.white)
        .background(Color(.sRGB,red: 62/255.0, green: 173/255.0, blue: 247/255.0))
        .clipShape(RoundedRectangle(cornerRadius: 8))
    }
}

注意:frame属性写在Text下方才可以使点击范围为整个摁钮区域,否则仅文字区域

样式二:圆角矩形边框包围(无背景色)

样式如图:
在这里插入图片描述

相应代码:

相当于在Button上套了一个圆角矩形形状的边框

struct ContentView: View {
    var body: some View {
        Button {
            print("close")
        } label: {
            HStack{
                Image("Off")

                Text("关闭")
                    .bold()
                    .font(Font.system(size: 22))
                    .frame(width:300, height: 80, alignment: .center)
            }
        }
        .foregroundColor(Color(.sRGB,red: 62/255.0, green: 173/255.0, blue: 247/255.0))
        //Button边框
        .overlay(
        RoundedRectangle(cornerRadius: 10, style: .continuous)
        //边框线
        .stroke(Color(.sRGB,red: 62/255.0, green: 173/255.0, blue: 247/255.0), lineWidth: 2)
        )
    }
}

样式三:圆角矩形边框包围(带背景色)

样式如图:
在这里插入图片描述

相应代码:

需要添加Button圆角矩形的背景色,那需要添加一个cornerRadius的圆角角度,
并且在cornerRadius上方添加背景色,否则背景色的覆盖区域则是个矩形,无法展示圆角

struct ContentView: View {
    var body: some View {
        Button {
            print("close")
        } label: {
            HStack{
                Image("Off")

                Text("关闭")
                    .bold()
                    .font(Font.system(size: 22))
                    .frame(width:300, height: 80, alignment: .center)
            }
        }
        .foregroundColor(Color(.sRGB,red: 62/255.0, green: 173/255.0, blue: 247/255.0))
        //Button边框
        .background(Color.red.opacity(0.3))
        .cornerRadius(10)
        .overlay(
        RoundedRectangle(cornerRadius: 10, style: .continuous)
        .stroke(Color(.sRGB,red: 62/255.0, green: 173/255.0, blue: 247/255.0), lineWidth: 2)
        )
        
    }
}

以上三种样式均为日常开发常用样式,以供大家参考选择。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淡酒交魂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值