10

My app has a TabView (PageTabViewStyle) and within each tab is a UIViewRepresentable. I have simplified the code to produce a minimum reproducible example below. The problem is that makeUIView is being called multiple times when it appears, and again multiple times when swiping through the pages.

FYI, this was not an issue in iOS 14.0 but is happening in iOS 14.2. I am using Xcode 12.2 Release Candidate at the moment.

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
    }

}

When the screen appears, the console prints:

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

And when I swipe to the right once, it prints:

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
nicksarno
  • 3,850
  • 1
  • 13
  • 33

1 Answers1

0

You must implement this method and use it to create your view object. Configure the view using your app’s current data and contents of the context parameter. The system calls this method only once, when it creates your view for the first time. For all subsequent updates, the system calls the updateUIView(_:context:) method. Hope this helps. https://developer.apple.com/documentation/swiftui/uiviewrepresentable/makeuiview(context:)

yoliO
  • 9
  • 1
  • 4