跳转至
Structure

UIViewRepresentableContext

Contextual information about the state of the system that you use to create and update your UIKit view.

Declaration

struct UIViewRepresentableContext<Representable> where Representable : UIViewRepresentable

Overview

A UIViewRepresentableContext structure contains details about the current state of the system. When creating and updating your view, the system creates one of these structures and passes it to the appropriate method of your custom UIViewRepresentable instance. Use the information in this structure to configure your view. For example, use the provided environment values to configure the appearance of your view. Don't create this structure yourself.

This structure contains 3 values:

Context-aware UIViewRepresentables

SwiftUI heavily relies on the environment, by way of environment objects (environmentObject(_:)) and environment values (EnvironmentValues). Environment values are useful for creating intelligent and context-aware UIKit ports.

For example, we can remove the isAnimated parameter from ActivityIndicator, and use isEnabled from the environment instead via EnvironmentValues's isEnabled:

struct ActivityIndicator: UIViewRepresentable {
    typealias Context = UIViewRepresentableContext<Self>
    typealias UIViewType = UIActivityIndicatorView

    public func makeUIView(context: Context) -> UIViewType {
        UIActivityIndicatorView(style: .medium)
    }

    public func updateUIView(\_ uiView: UIViewType, context: Context) {
        if context.environment.isEnabled && !uiView.isAnimating {
            uiView.startAnimating()
        }
        if !context.environment.isEnabled && uiView.isAnimating {
            uiView.stopAnimating()
        }
    }
}

Availability

iOS 13.0+

tvOS 13.0+

Topics


Instance Property

coordinator The view's associated coordinator.

environment The current environment.

transaction The current transaction.