1
struct MyShimmer: View {
    @State var show = false

    var body: some View {
        ZStack {
            Color.black
            VStack {
                ZStack {
                    Text("Chao")
                        .foregroundColor(Color.white.opacity(0.5))
                        .font(.system(size: 40))
                    Text("Chao")
                        .foregroundColor(Color.white)
                        .font(.system(size: 40))
                        .mask(
                            Color.red.opacity(0.5)
                                .frame(width: 20)
                                .offset(x: self.show ? 180 : -130)
                        )
                }
                .onAppear(){
                    DispatchQueue.main.async {
                        withAnimation(Animation.default.speed(0.15).delay(0).repeatForever(autoreverses: false)){
                            self.show.toggle()
                        }
                    }
                }
            }
        }
    }
}

The problem is, if i comment out DispatchQueue.main.async, the whole view scales out from the top left corner or the screen.

if I put a button somewhere and do the withAnimation task without DispatchQueue.main.async when the button is clicked, it works fine

Anyone knows what happens?

i'm using XCode(Version 12.5.1 (12E507)) my mac is running macos big sur 11.4 (20F71)

Chao Huang
  • 13
  • 3
  • Where does 'self.show.toggle()' come from? – El Tomato Aug 23 '21 at 02:53
  • 1
    I assume this is inside a `NavigationView`? I'm not completely sure, but I think `DispatchQueue.main.async {` runs the animation on a separate run loop, once the position of everything is laid out. I don't know *why* this is necessary though. Most likely a bug. – aheze Aug 23 '21 at 04:13
  • works without any problems for me using macos 12, xcode 13, targets macos 12 and ios15, with and without DispatchQueue. It maybe a bug on older systems. You could try adding the .onAppear() to the ZStack. – workingdog support Ukraine Aug 23 '21 at 05:15
  • agree with @aheze, looks like `NavigationView` bug, doubt there's anything you can do – Phil Dukhov Aug 23 '21 at 06:38
  • correction: it does not work for me without the DispatchQueue, if wrapped in a NavigationView. But if you were on ios15/macos12, then you could use `.task {..}` instead of `.onAppear{..}` to make it work without the DispatchQueue. – workingdog support Ukraine Aug 23 '21 at 07:12
  • yes, this View is inside a NavigationView. I'm just curious. Maybe it's just a bug @aheze – Chao Huang Aug 23 '21 at 09:50
  • Similar question: https://stackoverflow.com/q/64566492/14351818 – aheze Aug 24 '21 at 14:17

0 Answers0