I'm using UIKit picker in SwiftUI. To minimize the memory concerns with my picker's large number of values in my project, I decided to move UIKit picker in SwiftUI. When I quickly scroll the picker from top to bottom and vice versa, my picker occasionally leaps to the next value from the top or from bottom to the next/previous value. Steps to reproduce: Create a UIKit picker in SwiftUI Scroll the picker quickly from top to bottom and vice versa Intermittently, the selected value moves to the next value in the picker Code: Below attached sample code for reference
@State private var isPresented = false
@State private var selection: [Int] = [5]
@State var visiblePicker: Bool = false
private let data: [[String]] = [
Array(0...10).map { "\($0)" }
]
var body: some View {
VStack(spacing: 5) {
Button("Picker") {
self.isPresented = true
}
Text("\(self.data[0][self.selection[0]])")
.onTapGesture {
self.visiblePicker.toggle()
}
}
PickerView(data: self.data, selections: self.$selection)
}
}
struct PickerView: UIViewRepresentable {
var data: [[String]]
@Binding var selections: [Int]
func makeCoordinator() -> PickerView.Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<PickerView>) -> UIPickerView {
let picker = UIPickerView(frame: .zero)
picker.dataSource = context.coordinator
picker.delegate = context.coordinator
return picker
}
func updateUIView(_ view: UIPickerView, context: UIViewRepresentableContext<PickerView>) {
for i in 0...(self.selections.count - 1) {
print("UpdateUIView: \(self.selections[i])")
view.selectRow(self.selections[i], inComponent: i, animated: false)
}
}
class Coordinator: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
var parent: PickerView
init(_ pickerView: PickerView) {
self.parent = pickerView
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return self.parent.data.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.parent.data[component].count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.parent.data[component][row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("selected row = \(row)")
self.parent.selections[component] = row
}
}
}
pickerView(_:didSelectRow:inComponent:) while give you the currently selected row while pickerView(_:titleForRow:forComponent:) will gave you scrolling value. You might want to use that instead.