iosswiftxcodeswiftuiswift5

How to check if a view is displayed on the screen? (Swift 5 and SwiftUI)


I have a view like below. I want to find out if it is the view which is displayed on the screen. Is there a function to achieve this?

struct TestView: View {
    var body: some View {
        Text("Test View")
    }
}

Solution

  • You could use onAppear on any kind of view that conforms to View protocol.

    struct TestView: View {
        @State var isViewDisplayed = false
        var body: some View {
            Text("Test View")
            .onAppear {
                self.isViewDisplayed = true
            }
            .onDisappear {
                self.isViewDisplayed = false
            }
        }
    
        func someFunction() {
            if isViewDisplayed {
                print("View is displayed.")
            } else {
                print("View is not displayed.")
            }
        }
    }
    

    PS: Although this solution covers most cases, it has many edge cases that has not been covered. I'll be updating this answer when Apple releases a better solution for this requirement.