如何在SwiftUI中增加导航条项目(navigationBarItem)的可点击区域?

5

我有一个针对我的视图的代码

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的样式如下所示: enter image description here

当我点击resetButton时,似乎只有黄色区域能响应触摸。

我该如何扩大此按钮的可点击区域?(使其行为类似于普通的UIBarButtonItem

2个回答

12

您可以更改按钮内部的 view 的框架:

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

1
谢谢。然而这并没有解决问题。即使黄色区域变得更大,它的角落仍然无法响应触摸。此外,图像偏移量甚至更向左。 - 0rt
哦,抱歉我的错。我手打的时候漏了一行。我改变了答案。 - Mojtaba Hosseini
1
无法相信苹果没有提供关于如何完成此操作的示例。已接受的答案有效(感谢@MojtabaHosseini),但它似乎比应该做的更费力。 - SiPe

4

这篇博客文章 指引我正确的方向,我需要直接为图片添加一些填充。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接