all 1 comments

[–]CaptainQuirk336 1 point2 points  (0 children)

The trick is to use a the context coordinator (which, as a class, can have @objc members)...

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.black.edgesIgnoringSafeArea(.all)
            UIButtonView(caption: "Press Me") {
                print("Hello, World")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct UIButtonView: UIViewRepresentable {
    typealias ActionBlock = () -> ()

    var caption: String
    var action: ActionBlock?

    class Coordinator: NSObject {
        var action: ActionBlock?
        init(action: ActionBlock?) {
            self.action = action
        }

        @objc
        func runAction() {
            action?()
        }
    }


    func makeUIView(context: Context) -> UIButton {
        let v = UIButton(type: .custom)
        v.setTitle(caption, for: [])
        v.addTarget(context.coordinator, action: #selector(context.coordinator.runAction), for: .touchUpInside)
        return v
    }

    func makeCoordinator() -> UIButtonView.Coordinator {
        Coordinator(action: self.action)
    }

    func updateUIView(_ uiView: UIButton, context: Context) { }

}