偏移NavigationStack时出现异常卡顿及标题跳转问题
问题原因
直接给整个NavigationStack添加offset修饰符会干扰其内部导航栏的布局计算逻辑。向下偏移时,导航栏的自动布局调整(比如标题显示模式的隐式切换)会触发布局重算,导致标题出现约10像素的跳转;向上偏移时的延迟则是因为导航栏的布局缓冲机制。
修复方案1:将偏移应用到内部内容而非整个NavigationStack
把offset移到NavigationStack内部的内容容器上,让NavigationStack自身布局不受影响,导航栏就能保持稳定:
struct ContentView: View { @State private var offset = CGSize.zero var body: some View { NavigationStack { // 用VStack包裹内部内容,将offset应用在这里 VStack { Text("TEst") } .navigationTitle("Home") .offset(y: offset.height) } Text("Hello") .highPriorityGesture( DragGesture(minimumDistance: 1, coordinateSpace: .named("Grid")) .onChanged { gesture in offset = gesture.translation } .onEnded { _ in withAnimation{ offset = .zero } } ) } }
修复方案2:固定导航标题显示模式
通过navigationBarTitleDisplayMode固定标题的显示模式,消除自动切换带来的布局计算差异:
struct ContentView: View { @State private var offset = CGSize.zero var body: some View { NavigationStack { Text("TEst") .navigationTitle("Home") // 固定标题为大标题模式,也可设为.inline .navigationBarTitleDisplayMode(.large) } .offset(y: offset.height) Text("Hello") .highPriorityGesture( DragGesture(minimumDistance: 1, coordinateSpace: .named("Grid")) .onChanged { gesture in offset = gesture.translation } .onEnded { _ in withAnimation{ offset = .zero } } ) } }
说明
方案1更推荐,因为它从根源上避免了对NavigationStack整体布局的干扰,适用于所有标题显示模式;方案2则通过固定布局规则消除跳转,适合需要保留NavigationStack整体偏移的场景。
内容的提问来源于stack exchange,提问作者Allleex
相关产品推荐
相关产品推荐

