Skip to content

Instantly share code, notes, and snippets.

@insidegui
Created August 10, 2022 18:13
Show Gist options
  • Select an option

  • Save insidegui/97d821ca933c8627e7f614bc1d6b4983 to your computer and use it in GitHub Desktop.

Select an option

Save insidegui/97d821ca933c8627e7f614bc1d6b4983 to your computer and use it in GitHub Desktop.

Revisions

  1. insidegui created this gist Aug 10, 2022.
    40 changes: 40 additions & 0 deletions PlatformViewRepresentable.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    import SwiftUI

    #if os(iOS) || os(tvOS)
    public typealias PlatformView = UIView
    public typealias PlatformViewRepresentable = UIViewRepresentable
    #elseif os(macOS)
    public typealias PlatformView = NSView
    public typealias PlatformViewRepresentable = NSViewRepresentable
    #endif

    /// Implementers get automatic `UIViewRepresentable` conformance on iOS
    /// and `NSViewRepresentable` conformance on macOS.
    public protocol PlatformAgnosticViewRepresentable: PlatformViewRepresentable {
    associatedtype PlatformViewType

    func makePlatformView(context: Context) -> PlatformViewType
    func updatePlatformView(_ platformView: PlatformViewType, context: Context)
    }

    #if os(iOS) || os(tvOS)
    public extension PlatformAgnosticViewRepresentable where UIViewType == PlatformViewType {
    func makeUIView(context: Context) -> UIViewType {
    makePlatformView(context: context)
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
    updatePlatformView(uiView, context: context)
    }
    }
    #elseif os(macOS)
    public extension PlatformAgnosticViewRepresentable where NSViewType == PlatformViewType {
    func makeNSView(context: Context) -> NSViewType {
    makePlatformView(context: context)
    }

    func updateNSView(_ nsView: NSViewType, context: Context) {
    updatePlatformView(nsView, context: context)
    }
    }
    #endif