SwiftUI:视图短暂闪烁白色

时间:2020-10-14 22:44:33

标签: swift swiftui uikit

我是SwiftUI初学者,遇到以下问题:

我有两个视图,一个视图(矩形)和一个Web视图(WKWebView)。

使用这两个视图:

var body : some View {
    ZStack {
        WebView(self.webView)
        Rectangle()
            .foregroundColor(self.state.isLoading ? self.loadingColor : Color.clear)
    }
    .onAppear {
        // Initialize web view etc.
        // Sets self.state.isLoading to false after some time has passed
    }
}

有趣的是,当self.state.isLoadingtrue变为false时,UI短暂闪烁白色。

我不知道为什么会这样,特别是因为WebView在显示时肯定不是白色。

我尝试添加背景矩形并设置self.webViewself.webView.scrollView的backgroundColor:

var body : some View {
    ZStack {
        Rectangle()
            .foregroundColor(Color.red)
        WebView(self.webView)
        Rectangle()
            .foregroundColor(self.state.isLoading ? self.loadingColor : Color.clear)
    }
    .onAppear {
        // Initialize web view etc.
        self.webView.backgroundColor = UIColor.red
        self.webView.scrollView.backgroundColor = UIColor.red
        // Sets self.state.isLoading to false after some time has passed
    }
}

我希望看到一个简短的红色屏幕,但仍然是白色。

在Rectangle()过渡中添加动画可以使闪烁消失

Rectangle()
    .foregroundColor(self.state.isLoading ? self.loadingColor : Color.clear)
    .animation(.easeIn)

我错过了什么还是做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为这可能与self.state.isLoading变量有关,当它更改时,整个视图将重新加载。您是否可以尝试在结构中使isLoading成为局部变量(@State var isLoading:Bool = false),然后切换该局部变量?