如何在SwiftUI中增加按钮的大小?(多平台项目)

3

我正在尝试在SwiftUI中增加一个按钮的大小,Xcode 12.5中的多平台项目:

Button("Click me") {
            // Perform action here
        }
        .frame(width: 100, height: 100)
        .background(Color.yellow)
        .buttonStyle(BorderlessButtonStyle())

在查看了API后,我发现可以为按钮添加样式,但是我不知道如何扩大点击区域,使整个黄色框都能响应点击事件而不仅仅是标签。
编辑: 这里很好地解释了触摸区域的问题: tap problem 但那里的解决方案只适用于iOS项目,在Multiplatform项目中,按钮的框架大小不正确: enter image description here
Button(action: {}, label: {
           Text("Click me")
                    .frame(width: 100, height: 100)
                    .background(Color.yellow)
        })

使用比例效果,但我仍然不清楚您需要的具体内容。 - Tushar Sharma
我想要这个按钮更大。在当前版本中,这是多么困难令人沮丧啊。所有来自旧版本的示例都不起作用。缩放效果会产生不同的问题。我将把它添加到问题中。我也找到了一个在当前版本中有效的答案。 - kiatra
也许是 .buttonStyle(PlainButtonStyle()) - 它会消除所有默认样式。 - aheze
3个回答

2
这是一个可能的解决方案。
对于iOS:

enter image description here

 Button(action: {
                //add actions at here
            }) {
                VStack {
                    Text("Name")
                }.frame(width: 100, height: 100)
                .background(Color.yellow)
                .cornerRadius(20)
                
            }

适用于 macOS(macOS 版本也适用于 iOS 版本)

struct ContentView: View {
  
    var body: some View {
        VStack{
         
            
            Button(action: {
                //add actions at here
            }) {
                VStack {
                    Text("Button Name")
                }.frame(width: 100, height: 100)
                .background(Color.yellow)
                .cornerRadius(20)
                
            }.buttonStyle(CustomButtonStyle())
        }
    }
}

struct CustomButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(Color.blue)
            .cornerRadius(10.0)
            .padding()
    }
}

你测试过这个吗?这个解决方案的填充方式是错误的,就像大多数其他解决方案一样。它会导致我发布的第二张图片。 - kiatra
@kiatra,在iOS上测试没有问题。你是想在macOS上实现这个吗? - Seungjun
1
@Seugjun,我已经在一个多平台项目中进行了测试。你是正确的,它确实可以在iOS平台项目中工作。 - kiatra
@kiatra 你好,我更新了我的答案,现在也包括 macOS,请再检查一下? - Seungjun

1
我发现添加contentShape似乎是解决问题的方法:
Button(action: doSomething) {
        Text("Click me")
           .frame(width: 100, height: 100)
           .contentShape(Rectangle())
    }
    .background(Color.yellow)
    .buttonStyle(PlainButtonStyle())

0

该按钮无法识别该位置上的修饰符。解决方案如下:

        Button(action: {}, label: {
            Text("Click me")
                .frame(width: 100, height: 100)
                .background(Color.yellow)
        })

这个解决方案只适用于iOS。我已经编辑了问题,添加了我制作了一个多平台项目的信息。 - kiatra

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