SwiftUI分段控件在导航栏搭配Liquid Glass时存在显示bug
修复SwiftUI导航栏中分段控件的Liquid Glass渲染异常
当分段控件(Segmented Picker)置于导航栏内时,Liquid Glass材质的背景会和控件的渲染层级冲突,导致胶囊垂直裁剪、侧边出现分层背景的问题。以下是几种可行的修复方案:
方案1:给分段控件添加匹配导航栏的背景
为导航栏内的Picker添加.bar背景,让控件和导航栏背景融合,避免层级冲突:
ToolbarItem(placement: .navigation) { Picker(selection: $selectedOption) { ForEach(options, id: \.self) { option in Text(option).tag(option) } } label: { } .pickerStyle(.segmented) .fixedSize() .background(.bar) // 添加背景匹配导航栏 }
方案2:调整导航栏背景为实色
如果不需要Liquid Glass效果,可以直接设置导航栏背景为实色,彻底解决渲染冲突:
NavigationStack { // ... 原有页面内容 ... } .toolbarBackground(.bar, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar)
方案3:更换ToolbarItem的放置位置
.navigation位置的布局空间可能不足以适配分段控件,换成.principal这类更适配的放置位置也能避免裁剪问题:
ToolbarItem(placement: .principal) { // 修改放置位置 Picker(selection: $selectedOption) { ForEach(options, id: \.self) { option in Text(option).tag(option) } } label: { } .pickerStyle(.segmented) .fixedSize() }
异常效果展示

原问题代码
struct ContentView: View { let options = ["Left", "Right"] @State var selectedOption = "Left" var body: some View { NavigationStack { VStack { Picker(selection: $selectedOption) { ForEach(options, id: \.self) { option in Text(option).tag(option) } } label: { } .pickerStyle(.segmented) .fixedSize() Text(selectedOption) Spacer() } .padding() .toolbar { ToolbarItem(placement: .navigation) { Picker(selection: $selectedOption) { ForEach(options, id: \.self) { option in Text(option).tag(option) } } label: { } .pickerStyle(.segmented) .fixedSize() } } } } }
内容的提问来源于stack exchange,提问作者Siegfoult
相关产品推荐
相关产品推荐

