1

I have problem with making a selection with a wheelPicker if timer is running simultaneously.

A) default as runloop mode of timer:

the wheelPicker works fine and updates $selection But the counter in my ContenView won't keep counting while the wheelPicker is spinning

B) common as runloop mode of timer

the counter keeps counting while I interact with the wheelPicker, but the wheel pickers selection can't be changed if the timer fires before the picker is done spinning.

Here is my class holding the timer:

import Foundation

class MyTimer: ObservableObject {
    private var timer : Timer?
    @Published var counter : Int = 0
    
    public func launchTimer(){
        self.timer = Timer.scheduledTimer( withTimeInterval: 0.2, repeats: true, block:{_ in
            self.counter += 1
        })

        
        if self.timer != nil {
            RunLoop.current.add(timer!, forMode: .common)

        }
    }
}

Here is my contentView

import SwiftUI

struct ContentView: View {
    @StateObject var myTimer : MyTimer = MyTimer()
    @State var selecion : Int = 0
    
    var body: some View {
        
        VStack {
            Text("counter: \(myTimer.counter)")
                .padding()
            Text("selection: \(self.selecion)")
                .padding()
            
            Picker(selection: $selecion, label: Text("picker") ) {
                ForEach(0..<50, id: \.self) { id in
                    Text(String(id))
                }
            }
            .pickerStyle(WheelPickerStyle())

            Button(action: {
                myTimer.launchTimer()
            }, label: {
                Text("launch timer")
            })
        }
    }
}

I am fully aware, the code above has other issues, since the Timer could be scheduled multiple times. But I hope it is sufficient for illustrational purposes.

nevrx
  • 37
  • 6
  • The `scheduled` timer is added to the runloop by the framework. If you want to do it yourself you have to use the *unscheduled* API – vadian Mar 23 '21 at 21:46
  • @vadian not sure if I understood you correctly? Are you suggesting to change the timer initialiser to this: ```self.timer = Timer(timeInterval: 0.2, repeats: true, block:{_ in …``` Unfortunately this doesn't work, the ```selection var``` can't be updated if the timer fires before the wheelPicker is ready. – nevrx Mar 24 '21 at 21:21

0 Answers0