You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中ForEach循环内使用NavigationLink点击无响应问题

问题解决方法
  • 移除NavigationLink内部的Button:
    SwiftUI的NavigationLink本身就是可点击的交互容器,不需要额外嵌套Button,否则Button会拦截点击事件导致NavigationLink无法触发跳转。直接将按钮样式代码放到NavigationLink的label区域即可,示例代码如下:

    ForEach(userData) { user in
        NavigationLink(destination: DestinationView(userData: user.data)) {
            // 原来的button styling代码直接放在此处
            Text(user.name)
                .padding()
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(8)
        }
    }
    
  • 若需保留Button(添加额外点击逻辑):
    通过@State变量手动控制NavigationLink的激活状态,实现按钮点击逻辑+页面跳转的组合需求,示例代码如下:

    @State private var selectedUser: UserDataType? = nil
    
    var body: some View {
        NavigationStack { // iOS 16+使用,旧版本替换为NavigationView
            ForEach(userData) { user in
                Button(action: {
                    // 在此添加额外点击逻辑,比如埋点、状态更新等
                    selectedUser = user
                }) {
                    // button styling代码
                    Text(user.name)
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(8)
                }
            }
            .background(
                NavigationLink(
                    destination: DestinationView(userData: selectedUser!.data),
                    isActive: Binding(
                        get: { selectedUser != nil },
                        set: { if !$0 { selectedUser = nil } }
                    )
                ) {
                    EmptyView()
                }
            )
        }
    }
    
  • 版本适配注意:
    iOS 16及以上系统建议使用NavigationStack替代NavigationView,避免旧API带来的交互兼容性问题。

内容的提问来源于stack exchange,提问作者user20134455

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:40:20