Search code examples
swiftuiuikituipickerview

Picker scroll through one element horizontally


I have a SwiftUI Picker in which an item is selected. The text of one element can be large, so I used UIKit UIPickerView and set the manual height to 100, but at some point it became not enough. Is it possible to make scrolling horizontal for each element?

I want to get something like this:

Picker("Items", select: self._selectItem) {
    ForEach(self.items, id: \.self) { item in
        ScrollView(.horizontal, showsIndicators: false) {
            Text(item.description)
        }
        .tag(item)
    }
}

Solution

  • That should work fine. If you only want to scroll one item, you would have to insert a check of the item length.

    let items = [
        "A long item text.",
        "And a even longer item text which is really going further.",
        "Another item text which is really going further."
    ]
    
    struct ContentView: View {
        
        @State private var select = ""
        
        var body: some View {
            VStack {
                Text("Make your selection!")
                
                List(items, id: \.self) { item in
                    ScrollView(.horizontal) {
                        Text(item)
                    }
                    .listRowBackground(item == select ? Color.red : Color.white)
                    .onTapGesture {
                        select = item
                    }
                }
            }
        }
    }