为什么在TabView中多次调用makeUIView?

时间:2020-11-10 04:06:57

标签: swift xcode swiftui ios14 swiftui-tabview

我的应用程序具有一个TabView(PageTabViewStyle),并且每个选项卡中都有一个UIViewRepresentable。我简化了代码,以在下面产生一个最小的可重现示例。问题在于,makeUIView出现时将被多次调用,而在页面中滑动时将被多次调用。

仅供参考,这不是iOS 14.0中的问题,而是在iOS 14.2中发生的。我目前正在使用Xcode 12.2 Release Candidate。

import SwiftUI

struct MakeUIViewTest: View {
    var body: some View {
        TabView {
            CustomViewRepresentable(color: .red, index: 0)
            CustomViewRepresentable(color: .blue, index: 1)
            CustomViewRepresentable(color: .gray, index: 2)
        }
        .tabViewStyle(PageTabViewStyle())
    }
}

struct MakeUIViewTest_Previews: PreviewProvider {
    static var previews: some View {
        MakeUIViewTest()
    }
}

struct CustomViewRepresentable: UIViewRepresentable {
    
    var color: UIColor
    var index: Int
            
    func updateUIView(_ uiView: UIViewType, context: Context) {
        
    }
    
    func makeUIView(context: Context) -> UIView {
        print("MAKING UI VIEW NOW. INDEX \(index)")
        let view = UIView(frame: .zero)
        view.backgroundColor = color
        return view
    }

}

出现屏幕时,控制台将打印:

MAKING UI VIEW NOW. INDEX 0
MAKING UI VIEW NOW. INDEX 0
MAKING UI VIEW NOW. INDEX 0
MAKING UI VIEW NOW. INDEX 0
MAKING UI VIEW NOW. INDEX 0

当我向右滑动一次时,它会打印:

MAKING UI VIEW NOW. INDEX 1
MAKING UI VIEW NOW. INDEX 2
MAKING UI VIEW NOW. INDEX 1
MAKING UI VIEW NOW. INDEX 1
MAKING UI VIEW NOW. INDEX 1
MAKING UI VIEW NOW. INDEX 1
MAKING UI VIEW NOW. INDEX 2

0 个答案:

没有答案