我的应用程序有一个 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