Xcode 12中SwiftUI预览无法高亮NavigationView内嵌视图的问题咨询
Yep, this is absolutely a known bug in Xcode's SwiftUI preview system—you're not doing anything wrong! The preview's "click to jump to code" (and vice versa) functionality often breaks when views are wrapped in NavigationView or when using navigationBarTitle() modifiers, as the preview treats the entire navigation container as a single, unbreakable block instead of recognizing individual subviews.
Here are the most practical workarounds to get that super useful functionality back:
Extract subviews into separate
Viewstructs
This is my go-to fix because it also improves your code's modularity. By pulling the content insideNavigationViewinto its own dedicated view, the preview system can properly identify and link it to its code. For example:import SwiftUI // Independent subview that the preview can properly target struct HelloContentView: View { var body: some View { Text("Hello, World!") } } struct NavSample: View { var body: some View { NavigationView { HelloContentView() } } } struct NavSample_Previews: PreviewProvider { static var previews: some View { // Preview both the standalone subview and the full navigation view Group { HelloContentView() NavSample() } } }Now, clicking the
Textin either preview will jump straight to theHelloContentViewcode, and navigating from theHelloContentViewcode will highlight the correct preview element.Temporarily comment out
NavigationViewduring development
If you just need quick access to the jump functionality for a specific view, you can comment out theNavigationViewwrapper while working on that subview, then uncomment it when you're done. It's a bit manual, but it works for quick tweaks.Check where you apply the
navigationBarTitlemodifier
Sometimes applying the modifier directly to the subview instead of theNavigationViewitself can help the preview system distinguish elements. Try moving it:NavigationView { Text("Hello, World!") .navigationBarTitle("My Title") // Apply here instead of on NavigationView }Update to the latest Xcode version
Apple has been gradually fixing preview system bugs in newer releases. While this issue might not be fully resolved yet, newer versions (like Xcode 15+) often have improved preview behavior with navigation containers.
Unfortunately, there's no permanent fix for this bug from Apple yet, but these workarounds should let you keep using that invaluable jump-to-code feature even with navigation views in place.
内容的提问来源于stack exchange,提问作者Grant Lindsey

