首页 > 解决方案 > 用于 SwiftUI 2 的带有图像的按钮

问题描述

我想在视图中添加带有图像的按钮,例如带有 SwiftUI 2 图像的 twitter 按钮,但它没有填充到任何方向。

在此处输入图像描述

struct WeatherView: View {
var body: some View {
    
    VStack(alignment: .leading, spacing:0){
        
        Button(action: {}) {
                        Image("cloud")
                            .padding()
                            .background(Color.blue)
                            .foregroundColor(Color.white)
                            .clipShape(Circle())
                            .shadow(radius: 8)
                    }
    
    HStack(spacing: 5){
        
        Text("Rainy")
            .font(.largeTitle)
            .fontWeight(.medium)
        
        Spacer()
        
        Button(action: {
            
        }) {
            
            Image("menu").resizable().frame(width: 24, height: 24)
        }
        
    }
    .foregroundColor(Color("black"))
    .padding()
    Spacer()
   
}

}
}

有没有解决这个问题的方法。

标签: swiftui

解决方案


我希望你做得很好。

这段代码应该可以解决问题。

VStack {
    Spacer()
    Button(action: {}) {
        Image(systemName: "cloud.fill")
            .padding()
            .background(Color.blue)
            .foregroundColor(Color.white)
            .clipShape(Circle())
            .shadow(radius: 8)
    }
}
.frame(maxWidth: .infinity, alignment: .trailing)
.padding()

通过将按钮放在 VStack 中,并在其前面放置一个垫片,您会将按钮推到屏幕底部。然后通过在其上放置一个框架,并将宽度设置为 .infinity,并使其对齐尾随,您将进一步将按钮推到屏幕的尾端,在这种情况下,这会导致按钮位于右下角角落。

在此处输入图像描述

编辑:包含完整代码

struct WeatherView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack(spacing: 5) {
                Text("Rainy")
                    .foregroundColor(.black)
                    .font(.largeTitle)
                    .fontWeight(.medium)
                
                Spacer()
                
                Button(action: {}) {
                    Image("menu").resizable().frame(width: 24, height: 24)
                }
                
            }
            .foregroundColor(Color("black"))
            .padding()
            
            VStack {
                Spacer()
                Button(action: {}) {
                    Image("cloud")
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(Color.white)
                        .clipShape(Circle())
                        .shadow(radius: 8)
                }
            }
            .frame(maxWidth: .infinity, alignment: .trailing)
            .padding()
        }
    }
}

推荐阅读