I'm surprised this simple code still doesn't work on iOS 13.3 / Xcode 11.3. On my iPhone SE it's almost all off screen.
It's just two pieces of text, side by side, and two pickers, side by side. Anyone know a workaround?
struct ContentView: View {
@State var choice: Int = 10
@State var choice2: Int = 10
var body: some View {
return VStack {
HStack {
Text("Some text here")
Spacer()
Text("Foo baz")
}
HStack {
Picker(selection: self.$choice, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n) a").tag(n)
}
}
Picker(selection: self.$choice2, label: Text("C2")) {
ForEach(0..<10) { n in
Text("\(n) b").tag(n)
}
}
}
}
}
}
It looks like the Picker types are set to use the device width by default. That would match with the default behavior of UIPickerView I believe. This then causes the lower HStack to be 2 screens wide, and the upper HStack grows to match, pushing the text either side of the spacer to the far left & right, off the screen.
You can force the pickers to become narrower by using the .frame() modifier to specify a minimum width of 0, thus allowing them to shrink (by default they're fixed-size):
struct ContentView: View {
@State var choice: Int = 10
@State var choice2: Int = 10
var body: some View {
VStack {
HStack {
Text("Some text here")
Spacer()
Text("Foo baz")
}
HStack {
Picker(selection: $choice, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n) a").tag(n)
}
}
.frame(minWidth: 0)
Picker(selection: $choice2, label: Text("C2")) {
ForEach(0..<10) { n in
Text("\(n) b").tag(n)
}
}
.frame(minWidth: 0)
}
}
}
}
There's a slight visual artifact with this approach though, as it seems the semitransparent divider lines used to focus the selected row are still rendering full-width and are overlapping in the center of your view, making a darker line there. You can add a .hidden() modifier to one of the pickers to verify that.
Happily, there's a fix for that, too: tell the pickers to clip their contents with the .clipped() modifier:
Picker(selection: $choice2, label: Text("C2")) {
ForEach(0..<10) { n in
Text("\(n) b").tag(n)
}
}
.frame(minWidth: 0)
.clipped()
All will then be well with the world. Note though that there's a space between the pickers at this point. If you want them to line up perfectly (e.g. to mimic the multi-column appearance of a date/time picker) you'd need to set a spacing of zero on the containing HStack:
HStack(spacing: 0) {
...
}