对于那些想要使其成为死点的人,只需将两个HStack 放在每一侧,并使它们的宽度固定且相等。
将此方法添加到View 扩展。
extension View {
func navigationBarItems<L, C, T>(leading: L, center: C, trailing: T) -> some View where L: View, C: View, T: View {
self.navigationBarItems(leading:
HStack{
HStack {
leading
}
.frame(width: 60, alignment: .leading)
Spacer()
HStack {
center
}
.frame(width: 300, alignment: .center)
Spacer()
HStack {
//Text("asdasd")
trailing
}
//.background(Color.blue)
.frame(width: 100, alignment: .trailing)
}
//.background(Color.yellow)
.frame(width: UIScreen.main.bounds.size.width-32)
)
}
}
现在您有一个View modifier,它的用法与navigationBatItems(:_) 相同。您可以根据需要编辑代码。
使用示例:
.navigationBarItems(leading: EmptyView(), center:
Picker(selection: self.$choice, label: Text("Pick One")) {
ForEach(0 ..< self.choices.count) {
Text(self.choices[$0])
}
}
.pickerStyle(SegmentedPickerStyle())
}, trailing: EmptyView())
更新
存在leading 的问题,并且尾随项目违反了UINavigationBarContentView 的safeArea。在搜索时,我在answer 中遇到了另一个解决方案。它是一个名为SwiftUIX 的小助手库。如果您不想像我一样安装整个库,我为navigationBarItems 创建了一个gist。只需将文件添加到您的项目中。
但不要忘记这一点,它拉伸Picker 以覆盖所有可用空间并迫使StatusView 变窄。所以我不得不像这样设置框架;
.navigationBarItems(center:
Picker(...) {
...
}
.frame(width: 150)
, trailing:
StatusView()
.frame(width: 70)
)