Search code examples
swiftswiftuiapple-watchwatchoswatchos-6

SwiftUI — How can I display a countdown in a ScrollView?


I'm trying to make a SwiftUI app for Apple Watch that requires a countdown timer within a ScrollView. However, when I put a date formatter in a ScrollView, the app crashes (at least in the Simulator — I can't test on a real device because I have reached my app ID limit for a few days).

The code looks like this:

struct ContentView: View {
    let date = Date()
    
    var body: some View {
        ScrollView {
            Text(date, style: .timer)
        }
    }
}

And it gives me this runtime error: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Within a function called SwiftUI.DisplayList.ViewUpdater.ViewCache.setNextUpdate(_:item:state:tag:)


Solution

  • That seems to be a bug it seems worthy of a report.

    DateFormatter() seems to be a viable workaround.

    import SwiftUI
    
    struct TimerStyle: View {
        let date = Date()
        
        let timerFormat: DateFormatter
        
        init() {
            timerFormat = DateFormatter()
            timerFormat.dateFormat = "HH:mm:ss"
            
        }
        var body: some View {
            ScrollView {
                Text(date, formatter: timerFormat)
            }
        }
    }
    
    struct TimerStyle_Previews: PreviewProvider {
        static var previews: some View {
            TimerStyle()
        }
    }