iosswiftswiftui

SwiftUI: How can I increase the area in which a button can be triggered?


How can I increase the area in which a button can be triggered without changing the UI?

This is my code

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Text")

            .navigationBarTitle(Text("Title"))
            .navigationBarItems(
                leading:
                Button(action: { print("add") }) {
                    Image(systemName: SFSymbolName.plus)
                        .font(.system(size: 18))
                }
            )
        }
    }
}

Solution

  • For this particular situation, You can add padding to all edges excluding the leading edge to the label of the button:

    Button(action: { print("add") }) {
        Text("+")
            .padding(EdgeInsets(top: 20, leading: 0, bottom: 20, trailing: 50))
    }
    .background(Color.red) // This is just for seeing the hit area. You should get rid of it
    

    Note that the maximum tappable area should be inside the rectangle above the title:

    [Demo1

    Also, Note that only the area inside the bar will be tappable. So in the above sample, the overlap of the title and the overlap of the top of the bar will NOT be tappable!