选择器水平滚动一个元素

Picker scroll through one element horizontally

我有一个 SwiftUI 选择器,在其中选择了一个项目。一个元素的文本可能很大,所以我使用了 UIKit UIPickerView 并将手动高度设置为 100,但在某些时候它变得不够用了。是否可以让每个元素水平滚动?

我想得到这样的东西:

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

我强烈建议将拾取与文本显示和滚动分开,例如像这样:

struct ContentView: View {
    
    @State private var select = items[0]
    
    var body: some View {
        VStack {
            Text("Make your selection!")
            
            Picker("Items", selection: $select) {
                ForEach(items) { item in
                    Text(item.title)
                        .tag(item)
                }
            }
            
            ScrollView {
                Text(select.text)
            }
            .padding()
            .frame(height: 200)
        }
    }
}

那应该没问题。如果您只想滚动一个项目,则必须插入一个项目长度检查。

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
                }
            }
        }
    }
}