【问题标题】:Swiftui is there a way to change the clickable area of a buttonSwiftui 有没有办法改变按钮的可点击区域
【发布时间】:2020-01-07 19:35:28
【问题描述】:

有没有办法改变 swiftui 按钮的可点击区域? 我在检测到的文本区域上添加了一些按钮并想要单击它。 但是通过这段代码,我得到了这些结果

    var body: some View {
    HStack {
        ZStack{
            GeometryReader { geometry in
                Image(nsImage: self.img!)
                    .resizable()
                    .scaledToFit()
                    .background(self.rectReader())
            }
            ForEach(self.rects) { rect in
                Button(action: {
                    buttonPressed()
                }) {
                    Rectangle()
                    .fill(Color.init(.sRGB, red: 1, green: 0, blue: 0, opacity: 0.2))
                    .frame(width: rect.width, height: rect.height)
                }
                .offset(x: rect.xAxis, y: rect.yAxis)
            }
        }

可点击区域比我创建的矩形大很多。

【问题讨论】:

  • 为什么不把.onTapGesture直接加到Recatangle()呢?
  • 你真的让我大吃一惊!!!我会接受你的建议。不过,我正在使用 macos。
  • 成功了。再次非常感谢

标签: swift xcode swiftui


【解决方案1】:

https://stackoverflow.com/a/58422956/1334703

import SwiftUI

struct BlueButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(configuration.isPressed ? Color.blue : Color.white)
            .background(configuration.isPressed ? Color.white : Color.blue)
            .cornerRadius(6.0)
            .padding()
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World")
                .frame(maxWidth: .infinity, maxHeight: .infinity)

            Button(action: {
            }) {
                Text("Press")
                    .frame(maxWidth: 100, maxHeight: 24)
            }
            .buttonStyle(BlueButtonStyle())
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多