Explain the role of UIViewRepresentable in SwiftUI.
Instruction: Describe how UIViewRepresentable is used to integrate UIKit components into SwiftUI views.
Updated
Official answer
UIViewRepresentable wraps a UIKit UIView for use in SwiftUI. SwiftUI creates and updates the underlying view through the protocol callbacks; the wrapper value itself can be recreated many times. Use UIViewControllerRepresentable for a view controller such as UIPageViewController, rather than treating that controller as a UIView.
This complete view module wraps a label and updates it from SwiftUI state:
import SwiftUI
import UIKit
@MainActor struct UIKitLabel: UIViewRepresentable {
let text: String
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
label.font = .preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true
return label
}
func updateUIView(_ label: UILabel, context: Context) {
if label.text != text { label.text = text }
}
}
@MainActor struct LabelExample: View {
@State private var text = "Hello"
var body: some View {
VStack {
UIKitLabel(text: text)
Button("Change greeting") { text = "Welcome" }
}
.padding()
}
}
For controls that send delegate or target-action events, create a coordinator to forward those events to bindings or model actions. Keep its connection to the latest wrapper state current during updates, avoid feedback loops that rewrite unchanged values, and respect SwiftUI's update cycle instead of synchronously changing its state from an update callback.
Use dismantleUIView to remove observers, delegates or other resources that need explicit cleanup. The label here installs none and does not need custom teardown. Do not manually set the represented view's frame, bounds, center or transform in conflict with SwiftUI's layout; use supported sizing and surrounding layout instead.
Test state updates, identity changes, teardown, Dynamic Type and accessibility in the real UI. Successfully compiling the wrapper is not evidence of correct layout or interaction across devices.