SwiftUI如何消除NavigationBackButton与列表标题间的多余间距
你遇到的多余间距表现如下:

问题原因
问题根源是子视图重复嵌套了NavigationView,SwiftUI的导航栈仅需要在根视图(Home)初始化一次,所有子视图会自动共享该导航栈的上下文,子页面额外添加NavigationView会导致双层导航栏叠加,产生多余空白间距。
修复方案
仅需要删除example1.swift中多余的NavigationView嵌套即可,其余代码可保持不变:
home.swift(无需改动)
struct Home: View { var body: some View { NavigationView { List { NavigationLink( destination:example1(), label: { Text("to example1") } ) }.navigationBarTitle(Text("home")) }} }
example1.swift(删除冗余NavigationView)
struct example1: View { var body: some View { List { NavigationLink( destination:example2(), label: { Text("to example2") } ) }.navigationBarTitle(Text("example1")) } }
example2.swift(无需改动)
struct example2: View { var body: some View { Text("hello world") } }
可选微调方案
如果修复后仍有少量不想要的List默认边距,可给List添加.listStyle(.plain)修饰符消除系统默认的分组边距:
List { // 列表内容 } .listStyle(.plain)
内容的提问来源于stack exchange,提问作者Konsti_x08
相关产品推荐
相关产品推荐

