swiftuigeometryreaderswiftui-view

SwiftUI - Detect when global position of a View is changing


I am actually a beginner in SwiftUI. I want to know if there is a way to detect when the global position of a View is changing. For the moment I can get the global position of the view with GeometryReader, but I definitely can't detect when it is changing.

Thank you in advance for your help !

struct VideoView: View {

@State var player : AVPlayer // It is a video player
@State var isplaying = false
@State var showcontrols = false // Don't show controls
@State var value : Float = 0


var body: some View {
    
    GeometryReader { geo in
            VStack{
                
                ZStack{
                    VideoPlayer(player: $player)
                    
                }
                .frame(height: UIScreen.main.bounds.height)
            }
            .background(Color.black.edgesIgnoringSafeArea(.all))
            #IF GLOBAL POSITION OF THIS VIEW IS CHANGING
                if(geo.frame(in: .global).midY < 400){
                    self.player.play()
                    self.isplaying = true
                }
            }
            #ENDIF
        
        
    }
}

}


Solution

  • var body: some View {
        GeometryReader { geometry in
            Text("Hello")
                .onChange(of: geometry.frame(in: .global)) { newFrame in
                    // do something with newFrame
                }
        }
    }