I'm trying to add a three-component Picker (UIPickerView) to a SwiftUI app (in a traditional UIKit app, the data source would return 3
from the numberOfComponents
method), but I can't find an example of this anywhere.
I've tried adding an HStack of three single-component Pickers, but the perspective is off from what it would be if they were all part of a single Picker.
The best solution I found - so far - is to port the original
UIPickerView
in SwiftUI, viaUIViewRepresentable
and a coordinator.Porting UIKit components to SwiftUI is discussed in this amazing WWDC 2019 video:
Integrating SwiftUI
Here's the result (see demo code at the bottom):
Implementation:
There are two bindings,
data
andselection
, that are passed down from the superview.data is an array of array of
Data
, e.g.Each array represent a picker component.
Each value in an array represent a row in a picker component.
selection is an array of
Data
, e.g.[10, 20, 30]
It represents the picker selection (across all components).
If one of the bindings changes, it triggers a redraw of all components.
Also, the selection is restored.
Demo:
This isn't quite as elegant but it doesn't involve porting over any UIKit stuff. I know you mentioned perspective was off in your answer but perhaps the geometry here fixes that
Using the geometry and fixing the size like this shows the two pickers neatly taking up half the width of the screen in each half. Now you just need to handle selection from two different state variables instead of one but I prefer this way as it keeps everything in swift UI