【问题标题】:Swift onTapGesture with NavigationLink带有 NavigationLink 的 Swift onTapGesture
【发布时间】:2021-09-17 19:02:05
【问题描述】:

我想在点击/触摸某个 NavigationLink 时执行一项功能。我认为.onTapGesture 或类似的东西会很有用,但是当我添加.onTapGesture 时,它永远不会在触摸我的 NavigationLink 时触发。我需要使用不同的事件处理程序还是有其他问题?

示例代码:

struct ExampleView: View {
    var body: some View {
        NavigationView() {
            NavigationLink(destination: Text("Destination")) {
                Text("Navigate")
            }
            .onTapGesture {
                print("Tapped")
            }
        }
    }
}

【问题讨论】:

标签: swift swiftui navigation event-handling


【解决方案1】:

您可以设置绑定到导航链接的 isActive 参数,然后使用 onChange 观察其值以实现您要查找的内容:

struct ContentView: View {

@State private var isSelected: Bool = false
@State var color: Color = Color.red

var body: some View {
    NavigationView() {
        NavigationLink(
            destination: Text("Destination"),
            isActive: $isSelected,
            label: {
                Text("Navigate")
            }
        )
        .onChange(of: isSelected, perform: { value in
            color = Color.blue
        })
        .background(color)
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多