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

iOS 18.4+中Toolbar搭配UIViewControllerRepresentable导致SwiftUI导航功能异常的问题咨询

iOS 18.4+中Toolbar搭配UIViewControllerRepresentable导致SwiftUI导航功能异常的问题咨询

最近在iOS 18.4及以上版本开发时,碰到了一个棘手的导航异常问题,想请教下大家这是系统Bug还是我代码写法有问题,以及有没有可行的 workaround。

具体问题是:只要SwiftUI的Toolbar中包含任何类型的UIViewControllerRepresentable,就会导致导航完全失效。一旦导航到包含这种Toolbar的页面后,后续无法继续跳转新页面;点击返回按钮时,按钮文字会变化(看起来像是触发了导航动作),但页面完全不更新。

而且这个问题只和Toolbar绑定——把UIViewControllerRepresentable放在页面的其他位置(比如主内容区)时,导航完全正常。之前的iOS版本都没出现过这个情况,升级到18.4+后突然就出现了,模拟器和真实设备上都能复现。

我有一些基于UIKit实现的自定义组件,用来弥补SwiftUI的某些功能限制,所以非常希望能继续使用这些UIViewControllerRepresentable的实现,不想完全替换掉。

下面是能复现问题的代码,只要新建一个iOS项目,把这段代码替换进去,在iOS 18.4+上运行就能看到问题:如果删掉.background(UIViewControllerRepresentableView())这一行,导航就完全恢复正常了。

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLinkView(layer: 1)
        }
    }
}

struct NavigationLinkView: View {
    let layer: Int
    
    var body: some View {
        NavigationLink("Navigate") {
            NavigationLinkView(layer: layer + 1)
        }
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Image(uiImage: .checkmark)
                    .background(UIViewControllerRepresentableView()) // 这行代码导致导航异常
            }
        }
        .navigationTitle("Layer \(layer)")
    }
}

private struct UIViewControllerRepresentableView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewControllerRepresentableViewController {
        UIViewControllerRepresentableViewController()
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerRepresentableViewController, context: Context) {}
}

private final class UIViewControllerRepresentableViewController: UIViewController {
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

想请教大家几个问题:

  • 这是iOS 18.4+的系统Bug吗?还是我的代码写法有什么错误?
  • 有没有办法在继续使用UIViewControllerRepresentable的前提下,绕过这个导航异常的问题?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 13:08:08