How to get a horizontal picker for Swift UI?

Viewed 3510
2 Answers

I ended up solving this using a horizontal scrollview, tap gestures, and state to track the selection.

@State private var index

var body: some View {

        return ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(0..<self.items.count, id: \.self) { i in
                    Text("\(i)")
                        .foregroundColor(self.index == i ? .red : .black)
                        .frame(width: 20, height: 20)
                        .gesture(TapGesture().onEnded({ self.index = i }))
                }
            }
        }
        .frame(width: self.width, alignment: .leading)
}

You can use the Rotation Effect on a Picker and on the Picker's content. Make sure to rotate the content 90 degrees opposite from the picker or else the content will be sideways. If the picker is too big, you can manually set a height of the picker by using frame(height: _). In my case, I used frame(maxHeight: _). You might need to adjust the row indicators by using clipped() after the resize to stop them from flowing out of the picker.

I'm using images as an example but it should work with most if not all basic views.

Code:

Picker(selection: $data, label: Text("Data")) {
    ForEach(dataArray, id: \.self) { imageName in
        Image(imageName)
        .resizable()
        .scaledToFit()
        .rotationEffect(Angle(degrees: 90))
    }
}
.labelsHidden()
.rotationEffect(Angle(degrees: -90))
.frame(maxHeight: 100)
.clipped()
Related