当我从UIKit导航到SwiftUI视图时,导航工具栏项目在一毫秒后出现。

4
这是我的简化的SwiftUI视图的样子:
struct NotificationsView: View {
    
    var body: some View {
        if #available(iOS 16.0, *) {
            notificationsView.toolbarRole(.editor)
        } else {
            notificationsView
        }
    }
    
    private var notificationsView: some View {
        NavigationView {
            ScrollView {
                
            }
        }.toolbar {
            ToolbarItem(placement: .principal) {
                Text("Notifications")
                    .font(.headline)
                    .foregroundColor(.gray)
            }
        }
    }
}

这个视图之前是一个UIKit视图,所以当我导航到NotificationsView时,标题需要一毫秒才会出现,返回按钮的文本会消失(这正是我想要的-只有箭头)。请参见gif: 标题在一毫秒后出现 以下是我显示NotificationsView的方法:
let view = notificationsViewProvider.create(notifications: notifications)
let vc = UIHostingController(rootView: view)
rootNavigationController.setNavigationBarHidden(false, animated: false)
rootNavigationController.show(vc, sender: self)

即使使用animated: true,它仍然相似,输出结果没有太大变化。
我在一个演示项目中尝试了这个方法,其中有两个视图,相同的代码运行良好,只是这两个视图都是SwiftUI。
对于如何修复这个问题有什么想法吗?

在导航控制器中添加一个导航视图。可以尝试移除导航视图,保持导航栏的显示。 - undefined
@PtitXav 你说得对。我试过了,但是结果还是一样。我还尝试了设置 vc.navigationItem.backButtonTitle = ""vc.navigationItem.backButtonDisplayMode = .minimal,但是没有起到作用。vc.navigationItem.title = "通知" 是可以的,但是我无法通过这种方式编辑颜色。 - undefined
1
赏金吸引了一个ChatGPT的剽窃者。 - undefined
1个回答

2
我能想到的最好的解决方案是不要混合使用SwiftUI和UIKit的导航栏。
由于您的初始视图是一个UIKit视图控制器,我更倾向于在整个导航过程中使用UIKit的导航栏。就像这样:
final class UIKitViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Configure the back button here
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
    
    func onPush() {
        let notificationsView = SwiftUINotificationsViewController(rootView: NotificationsView())
        navigationController?.pushViewController(notificationsView, animated: true)
    }
}

final class SwiftUINotificationsViewController: UIHostingController<NotificationsView> {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure the title here
        let titleLabel = UILabel()
        titleLabel.attributedText = .init(string: "Notifications", attributes: [
            .foregroundColor: UIColor.blue,
            .font: UIFont.systemFont(ofSize: 17.0, weight: UIFont.Weight.light)
        ])

        self.navigationItem.titleView = titleLabel
    }
}

struct NotificationsView: View {
    var body: some View {
        if #available(iOS 16.0, *) {
            notificationsView.toolbarRole(.editor)
        } else {
            notificationsView
        }
    }
    
    private var notificationsView: some View {
        ScrollView {
            // Setup your view
            // Don't use toolbar or any navigation item configuration here
        }
    }
}

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