Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Touchable Area of a Button

Tags:

xcode

swiftui

I am trying to increase the touchable area of a button inside a NavigationView. It does not work even though the area is made bigger. My code is below:

var body: some View {
NavigationView {
    List(taskStore.tasks) { tasks in
        Text(tasks.name)
    }
.navigationBarTitle("Tasks")
.navigationBarItems(
    trailing: Button(action: { 
    self.modalIsPresented = true 
}){
     Image(systemName: "plus")
    .frame(width: 200, height: 200)
    .contentShape(Rectangle())
    .background(Color.yellow)
})}

The green area is touchable and the red area isn't touchable.

enter image description here

I found a solution online that works. However this solution only works for a button that is NOT in the NavigationView. So if I put the button in "some view" like the following below, it works as per the solution:

var body: some View {
Button(action: {self.modalIsPresented = true} ) {
Text("Default padding")
.padding(50)
.background(Color.yellow)
}}}

But when I put the button in a Navigation View like my code, the yellow area is not touchable. How can I get the whole yellow area (red box) to be touchable like the solution?

Thanks :D

Example of solution: enter image description here


1 Answers

If you want a button in the navigation bar, it is only going to be clickable inside the navigation bar, no matter what you try to set the image's frame at, and the NavigationView determines that height, no matter what the children- the button, in this case- may want.

Historically, changing the height of the NavigationBar has not been supported: see the comments here

Now you could do something funky with ZStacks- put a button on top of the navigation view, perhaps- but you're not going to be able to put anything larger than the set height inside the navigation bar.

like image 101
SCooney Avatar answered Jan 23 '26 19:01

SCooney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!