在SwiftUI中的按钮上添加文本和图片

16

我试图在按钮上添加文本和图像,如下所示:

Button(action: {}) {
        Image("gift")
        Text("Send")
            .padding(.horizontal)
    }
    .padding()
    .foregroundColor(.white)
    .background(Color.gray)
    .cornerRadius(.infinity)

按钮外观:

enter image description here

但我想创建这个:

enter image description here

谢谢

3个回答

35

只需将ImageText放在HStack中即可...

Button(action: {}) {
    HStack {
        Image(systemName: "gift")
        Text("Send")
    }
}
.padding()
.foregroundColor(.white)
.background(Color.gray)
.cornerRadius(.infinity)

输入图像描述


0
从iOS 14开始,有一个标准视图可以实现这种布局:
Button(action: {}) {
  Label("Send", image: "gift")
    .padding()
    .foregroundColor(.white)
    .background(Color.gray)
    .cornerRadius(.infinity)
}

此外,将样式修饰符添加到Button视图中的内容中,可以使按钮的背景也可点击。将样式修饰符添加到按钮外部将导致只有图像和文本所占据的区域(Button视图的主体)可点击,而周围的按钮背景(灰色区域)不可点击。

-1

SwiftUI

对于按钮的 TextImageShadow,它们都可以正常工作。

Button(action: {

            }) {
                HStack {
                    Image(uiImage: UIImage(named: "Login")!)
                        .renderingMode(.original)
                        .font(.title)
                        .foregroundColor(.blue)
                    Text("Login")
                        .font(.title)
                        .foregroundColor(.white)
                }


                .font(.system(size: 15))

                .frame(minWidth: 0, maxWidth: .infinity)
                .background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
                .cornerRadius(40)
                .frame(width: 200, height: 60, alignment: .center)
                .shadow(color: .red, radius: 5, x: 0, y: 0)

            }

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接