Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase tappable area of navigationBarItem in SwiftUI?

Tags:

ios

swift

swiftui

I have this code for my view

struct ContentView: View {
    var body: some View {
        NavigationView{
            List{
                ForEach(0...5, id: \.self) { note in
                    VStack(alignment: .leading) {
                        Text("title")
                        Text("subtitle")
                            .font(.subheadline)
                            .foregroundColor(.secondary)
                    }
                }
            }
            .navigationBarItems(trailing: resetButton)
            .navigationBarTitle(Text("Notes"))
        }
    }

    var resetButton: some View {
        Button(action: {
            print("reset")
        }) {
            Image(systemName: "arrow.clockwise")
        }
        .background(Color.yellow)
    }
} 

resetButton looks like this: enter image description here

When I am tapping the resetButton, it seems like only the yellow area responds to touches.

How do I make tappable area of this button bigger? (Make it behave like a normal UIBarButtonItem)

like image 243
0rt Avatar asked Dec 04 '22 17:12

0rt


2 Answers

You can change the frame of the view inside the button:

var resetButton: some View {
    Button(action: {
        print("reset")
    }) {
        Image(systemName: "arrow.clockwise")
        .frame(width: 44, height: 44) // Or any other size you like
    }
    .background(Color.yellow)
}
like image 183
Mojtaba Hosseini Avatar answered Jan 03 '23 10:01

Mojtaba Hosseini


This blog post pointed me in the right direction, I needed to add some padding directly to the Image.

enter image description here

Button(action: {
    // Triggered code
}) {
    Image(systemName: "plus")
        .font(.system(size: 22, weight: .regular))
        .padding(.vertical)
        .padding(.leading, 60)
}
.background(Color.red) // Not needed
like image 24
CodeSnippets Avatar answered Jan 03 '23 08:01

CodeSnippets