在 SwiftUI 中以固有尺寸显示分段选取器

Ant*_*ton 10 picker width ios segmentedcontrol swiftui

在 SwiftUI 中,Pickerof 样式SegmentedPickerStyle占据其封闭视图的整个宽度。我怎样才能让它只占据它需要的宽度?

考虑一下: 分段拾取器 它是由以下代码生成的:

struct ContentView: View {
    @State var value = 1
    var body: some View {
        Picker("Value", selection: $value) {
            Text("One").tag(1)
            Text("Two").tag(2)
        }
        .pickerStyle(SegmentedPickerStyle())
        .padding()
    }
}
Run Code Online (Sandbox Code Playgroud)

如何从两个选择器选择中删除较大的边距,使选择器仅达到所需的宽度?这似乎是一个非常基本的问题,但我却找不到答案。

Asp*_*eri 29

使用固定大小,如下所示

演示

    Picker("Value", selection: $value) {
        Text("One").tag(1)
        Text("Two").tag(2)
    }
    .pickerStyle(SegmentedPickerStyle())
    .fixedSize()                           // << here !!
Run Code Online (Sandbox Code Playgroud)