Set continuous wheel picker - SwiftUI

Viewed 1319

How can I display a picker that can scroll either up or down infinitely inside a chosen range? Just like when you set an alarm in ios devices. Right now if I have a range between 0 and 60, I can only scroll up until I reach 60 and then scroll down to go back to 0. I want it to be continuous that when I reach 60 I have the loop starting over again.

1 Answers

You can simply add a large amount as the upper bound of your range and set the initial value to be half of it and get the resulting value truncating the reminder dividing it by 60 value % 60. To execute a method when the picker value changes you can use the approach shown in this [post][1]:

import SwiftUI

struct ContentView: View {
    @State private var selection = 300
    var minutes: Int { selection % 60 }
    var body: some View {
        Picker(selection: $selection, label: Text("Minutes:")) {
            ForEach(0 ..< 600) {
                Text(String(format: "%02d", $0 % 60))
            }
        }.onChange(of: selection, perform: valueChanged)
    }
    func valueChanged(_ value: Int) {
        selection = 300 + value % 60
        print("Minutes: \(minutes)")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Related