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

389 views Asked by At

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:)

3

There are 3 answers

0
lorem ipsum On BEST ANSWER

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()
    }
}
3
Ken On

this is the answer!!! just add

.clipped()

struct ContentView: View {
    var body: some View {
        ScrollView {
            Text(Date(), style: .timer)
                .clipped()
        }
    }
}
0
sash On
struct ContentView: View {
    var body: some View {
        ScrollView {
            Text(Date(), style: .timer)
                .clipped()
        }
    }
}