Language/Swift

[SwiftUI] UIViewRepresentable

jaewpark 2022. 9. 20. 14:00

UIViewRepresentable 

: A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.

 

Use this protocol to port a UIView from UIKit into SwiftUI

 

Setup

To conform to UIViewRepresentable, you must implement four main lifecycle functions:

  1. makeUIView(context:): Create and return an instance of your UIView Type here.
  2. updateUIView(_:context:): This is immediately called once after the call to makeUIView(context:), then called whenever any state changes.
  3. dismantleUIView(_:coordinator:): Upon destruction of the parent container, this gets called. (This is optional. A default implementation is provided.)
  4. makeCoordinator(): This creates a Coordinator for the view. (This is also optional.)

 

// ActivityIndicator.swift
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()
        }
    }
}


// ContenView.swift
struct ContentView: View {
    @State var isAnimating: Bool = false

    var body: some View {
        VStack {
            Toggle("Animating", isOn: $isAnimating)

            ActivityIndicator()
                .disabled(!isAnimating)
        }
    }
}

 


참고사이트

자세한 설명 : https://swiftontap.com/uiviewrepresentable