【问题标题】:How to check if a view is displayed on the screen? (Swift 5 and SwiftUI)如何检查屏幕上是否显示视图? (Swift 5 和 SwiftUI)
【发布时间】:2020-06-21 01:38:18
【问题描述】:

我有如下视图。我想知道它是否是屏幕上显示的视图。有没有实现这个的功能?

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

【问题讨论】:

  • 您希望将主动行为转变为 SwiftUI 的反应性质。在 SwiftUI 概念中,某些状态(或在视图模型中或在@State 中)决定了视图是否可见。所以有这样的状态你不需要问视图你直接使用它。
  • @Asperi 这不是设置可见性,而是检查视图当前是否在视口内以及用户是否可以看到它。

标签: ios swift xcode swiftui swift5


【解决方案1】:

您可以在任何符合 View 协议的视图上使用 onAppear。

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.")
        }
    }
}

【讨论】:

  • 谢谢,但有没有办法可以在函数中执行此操作,例如 private func () { if (TestView.isDisplayed()) {do something}}
  • 您需要指定您的要求是检查视图是否显示在外部函数中。
  • 我已根据您的要求修改了答案。
  • 谢谢我已经解决了。我会将您的答案标记为正确。 :)
  • 这并不是真正的屏幕显示。即使它没有显示在屏幕上也会被调用。只需加载视图,它就会调用.onAppear()
【解决方案2】:

您可以使用 GeometryReader 和 GeometryProxy 检查视图在全局范围内的位置。

        struct CustomButton: View {
            var body: some View {
                GeometryReader { geometry in
                    VStack {
                        Button(action: {
                        }) {
                            Text("Custom Button")
                                .font(.body)
                                .fontWeight(.bold)
                                .foregroundColor(Color.white)
                        }
                        .background(Color.blue)
                    }.navigationBarItems(trailing: self.isButtonHidden(geometry) ?
                            HStack {
                                Button(action: {
                                }) {
                                    Text("Custom Button")
                                } : nil)
                }
            }

            private func isButtonHidden(_ geometry: GeometryProxy) -> Bool {
    // Alternatively, you can also check for geometry.frame(in:.global).origin.y if you know the button height.
                if geometry.frame(in: .global).maxY <= 0 {
                    return true
                }
                return false
            }

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多