Mai pa
Mai pa

Reputation: 45

Open swiftUI view from UIKit code for rightBarItem

This is code of UIKit File.I want to open view which is editButtonCustomizeView and written in swiftUI. How can I take action of this button which navigates to swiftUI

override func viewDidLoad() { super.viewDidLoad()

let editButton = UIBarButtonItem(image: editImage, style: .Plain, target: self, action: editButtonCustomizeView())

}

Right now getting error is "Cannot convert value of type 'editButtonCustomizeView' to expected argument type 'Selector?' "

Upvotes: 0

Views: 566

Answers (1)

Thel
Thel

Reputation: 484

That is because the action expects a selector to point to what action is to be called when the button is tapped so you can't pass a view.

If you want to show a SwiftUI view when that button is tapped you have to first add a action to show the viewcontroller, then create the action to show the viewcontroller and lastly add you SwiftUI view in a viewcontroller so it can be used in UIKit.

Adding the action to the button:

let editButton = UIBarButtonItem(image: editImage, style: .Plain, target: self, action: #selector(showSwiftUIView))

Then the action to show the view:

@objc func showSwiftUIView(sender: UIControl) {
   let vc = editButtonCustomizeVC()
   present(vc, animated: true)
}

And lastly turn your view to a ViewController:

final class editButtonCustomizeVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let childView = UIHostingController(rootView: editButtonCustomizeView())
        addChild(childView)
        childView.view.frame = view.bounds
        view.addSubview(childView.view)
        childView.didMove(toParent: self)
        
    }

}

Upvotes: 0

Related Questions