For my use case i need to access the same intance of MyViewController ,which i am using in UIViewRepresentable for adding it to SwiftUI herierchy .And to achive that i am creating a static intance of MyViewController and using it in objective c function to make changes in viewcontroller as well as adding it in SwiftUI view hireiachy . Is this a right apprach to use ? I dont find any documentation by apple which suggest this approach .
Just want to validate it here .
And also Is this method of using UIRepresentableController right method to use in my UIkit's view controller in SwiftUI and updating viewcontroller from objectiveC ? or is there any other approach to achieve this ?
Entry Point :
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
SwiftUIView()
}
}
}
SwiftUIView:
import SwiftUI
struct SwiftUIView: View {
var body: some View {
UIKitToSwiftUIBridge ()
}
}
UIKitToSwiftUIBridge:
import SwiftUI
import UIKit
struct UIKitToSwiftUIBridge: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> MyViewController {
let viewcontroller = SharedViewController.sViewController
return viewcontroller
}
func updateUIViewController(_ uiViewController: MyViewController, context: Context) {
}
}
SharedViewController :
{
static let sViewController = MyViewController ()
private override init () {
}
@objc static func GetViewController ()->MyViewController
{
return SharedViewController.sViewController
}
}
MyViewController.swift :
import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .black
let button = UIButton (frame : CGRect (x:50, y:100, width:100, height:50))
button.setTitle("Button", for: .normal)
button.addTarget(self, action: #selector(ButtonAction (_:)), for: .touchDown)
}
@objc
func ButtonAction (_ sender :UIButton)
{
let view = UIView (frame: CGRect (x:0, y:0, width:300, height:400))
view.backgroundColor = .red
let label = UILabel (frame: CGRect(x: 60, y: 50, width: 150, height: 60))
label.text = " Label"
view.addSubview(label)
self.view.addSubview(view)
}
@objc
func ChangeColor () {
self.view.backgroundColor = .white
}
}
Objective C code where i need to access MyViewController's intance :
void ObjectiveC::ChangeColorOfViewController ()
{
dispatch_async( dispatch_get_main_queue (),^{
MyViewController * sharedobj = [SharedObject sharedMethod];
[sharedobj ChangeColor];
});
}