ios – SwiftUi overlay view stops animating


I have a camera built in swift and I want to allow the user to focus the camera on a certain spot. When the user clicks anywhere on the screen I want to display an animating view that represents a focus action. This view functions correctly but after clicking on multiple different spots on the screen then the view stops animating and freezes above the camera. I tried using dispatch queues so the view always goes away after the delay but this didn’t work.

struct HomeStory: View {
    @State var focusLocation: (CGFloat, CGFloat)?
    
    var body: some View {
        ZStack(alignment: .bottom) {
            CameraStoryView()
                .onTapGesture { tapP in
                    UIImpactFeedbackGenerator(style: .light).impactOccurred()
                    focusLocation = (tapP.x, tapP.y)
                    cameraModel.focus(at: CGPoint(x: tapP.x, y: tapP.y))
                }

            let w = widthOrHeight(width: true)
            let h = widthOrHeight(width: false)
            if let points = focusLocation, (points.0 > 20) && (points.0 < w - 20) && (points.1 > 80) && (points.1 < h - (h * 0.3)) {
                FocusView()
                    .position(x: points.0, y: points.1 - 35)
                    .onAppear {
                        let p1 = points.0
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
                            if (focusLocation?.0 ?? 0.0) == p1 {
                                focusLocation = nil
                            }
                        }
                    }
                    .offset(y: 35)
            }
     }
}
struct FocusView: View {
    @State var animate = false
    var body: some View {
        ZStack {
            Circle()
                .fill(.white.opacity(0.75))
                .frame(width: 70, height: 70)
                .scaleEffect(self.animate ? 1 : 0)
                .opacity(animate ? 0 : 1)
            
            Circle()
                .fill(.white)
                .frame(width: 7, height: 4)
                .scaleEffect(self.animate ? 7.0 : 1)
                .opacity(animate ? 0.3 : 1)
        }
        .onAppear {
            DispatchQueue.main.async {
                self.animate = true
            }
        }
        .onDisappear {
            DispatchQueue.main.async {
                self.animate = false
            }
        }
        .animation(.linear(duration: 0.7), value: animate)
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img