【问题标题】:How to increase the size of a Button in SwiftUI? (Multiplatform project)如何在 SwiftUI 中增加按钮的大小? (多平台项目)
【发布时间】:2021-05-18 11:12:14
【问题描述】:

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

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

检查API 后,我发现我可以设置按钮样式,但我不知道如何使点击框变大。这样整个黄框都接收到点击动作,而不仅仅是标签。

编辑:

点击区域问题在这里解释得很好:https://alejandromp.com/blog/playing-with-swiftui-buttons/

但是那里的解决方案是将元素添加到按钮并更改其大小仅适用于 iOS 项目。在多平台项目中,按钮的框架大小错误:

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

【问题讨论】:

  • 使用缩放效果,但我仍然不清楚你到底需要什么。
  • 我想要按钮啤酒。令人沮丧的是,在当前版本中这有多难。因为旧版本的所有示例都不起作用。规模效应确实会产生不同的问题。我会将它添加到问题中。我还找到了适用于当前版本的答案。
  • 也许.buttonStyle(PlainButtonStyle()) - 它摆脱了所有默认样式

标签: swiftui


【解决方案1】:

这是一个可能的解决方案

适用于 iOS

 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 ,在 iOS 中测试没有问题。您是否试图在 macOS 中实现这一目标?
  • @Seugjun ,我已经在一个多平台项目中进行了测试。你说得对,它确实适用于 iOS 平台项目。
  • @kiatra 嗨,我更新了我的答案以包括 macOS,你能再检查一次吗?
【解决方案2】:

我找到了这个解决方案,其中添加 contentShape 似乎可以解决问题:

Button(action: doSomething) {
        Text("Click me")
           .frame(width: 100, height: 100)
           .contentShape(Rectangle())
    }
    .background(Color.yellow)
    .buttonStyle(PlainButtonStyle())

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 此解决方案仅适用于 iOS。我已经编辑了问题以添加我制作了一个多平台项目。
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多