简体   繁体   中英

SwiftUI Touchable Area of a Button

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.

在此处输入图片说明

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: 在此处输入图片说明

I think you may find your desired effect inside the .navigationBarItems(trailing:) if you use .contentShape(Rectangle()) modifier. Or you could use other shapes to suit your needs. Then adjust the size of the .frame to adjust the tappable area as desired. Here is a quick code example.

struct ContentView: View {
var body: some View {
    NavigationView {
        List {
            Text("Hello, World")
        }
    .navigationBarTitle(Text("Items"))
        .navigationBarItems(trailing: Button(action: {
            print("Do Something")
        }, label: {
            Image(systemName: "plus")
                .frame(width: 100, height: 50)
                .contentShape(Rectangle())
                .border(Color.red, width: 3)
                .background(Color.gray)
        }))
    }
  }
}

I hope this helps.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM