Carlos Maria Caraccia
Carlos Maria Caraccia

Reputation: 500

Swiftui is there a way to change the clickable area of a button

Is there a way to change the clickable area of a swiftui button? I'm adding some buttons over the area of detected text and want to click it. But with this code I get these results

    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)
            }
        }

The clickable area is much larger than the rect I create.

enter image description here

Upvotes: 2

Views: 1955

Answers (1)

小弟调调
小弟调调

Reputation: 1333

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()
    }
}

Upvotes: 1

Related Questions