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.
Asked
Active
Viewed 2,162 times
2
-
Just create a huge amount of elements repeating the content and set the initial value the middle index – Leo Dabus Aug 10 '20 at 00:35
-
what's the point on create a huge elements? I just need to loop over numbers between 0 and 60. Imagine the roulette at casino, the values repeat themselves infinitely – xmetal Aug 10 '20 at 00:44
-
Just make a large value and use value % 60. That should be easy. – Leo Dabus Aug 10 '20 at 00:57
-
I don't really understand how can I do it, that might be very easy but how's the code to make it work like that? – xmetal Aug 10 '20 at 01:22
1 Answers
4
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()
}
}

Leo Dabus
- 229,809
- 59
- 489
- 571
-
1There's no need to use a custom extension. You can use [onReceive](https://stackoverflow.com/a/63946059/8697793) for SwiftUI 1 & 2 or [onChange](https://stackoverflow.com/a/63927989/8697793) for SwiftUI 2. – pawello2222 Sep 17 '20 at 20:58
-
I know I am late to the party, but the above answer seems like an elegant visual illusion, but if u have a diligent user that keeps scrolling they will eventually reach to the end of the scroller. – OverD Mar 12 '23 at 12:38