SwiftUI button added inside uikit view using hosting controller is not triggering a action

When i am using a swiftUI's button with the help of a UIHostingController inside a UIKit based view ,

Swift UI view with button : -

        @State var uTitle:String!
        @State var uFrame:CGRect!

        
        var body: some View {
  
            Button(action: {
                self.ButtonAction(pId: uId)
                  }) {
                      Text(uTitle)
                  }
         }
        
        func ButtonAction (pId:Int)
        {
            print ("Hello world !!!!!")
        }
    }

If i use above SwiftUIButton this way ( Adding button.frame.size ) :-

     let button:UIView!
     button = UIHostingController(rootView: SwiftUIButton (uTitle: "Button title")).view
      button.frame.origin = CGPoint(x: 50, y: 50)
      button.frame.size = CGSize(width: 150, height: 50)
      parentview.addSubview(button)

Button click action works fine.

But if i use button this way (not adding width height after intantiation of UIHostingController ,instead adding width height inside SwiftUIButton using .frame(widht: ,height:))

     let button:UIView!
     button = UIHostingController(rootView: SwiftUIButton (uTitle: "Button title")).view
      button.frame.origin = CGPoint(x: 50, y: 50)
     //   Removed frame.size 
      parentview.addSubview(button)
        @State var uTitle:String!
        @State var uFrame:CGRect!

        
        var body: some View {
  
            Button(action: {
                self.ButtonAction(pId: uId)
                  }) {
                      Text(uTitle)
                     // Added .frame property
                      .frame(width:150,height:50)

                  }
         }
        
        func ButtonAction (pId:Int)
        {
            print ("Hello world !!!!!")
        }
    }

Action is not triggering. What could be the issue?

I think the issue is that you apply frame on Text, not on the button. So the button has zero frame.

I would try to change to this:

        Button(action: {
            self.ButtonAction(pId: 10)
        }) {
            Text("uTitle")
        }
        .frame(width:150,height:50)            // .frame property added to Button

Please confirm if it works (mark the answer as correct), otherwise, please tell …

SwiftUI button added inside uikit view using hosting controller is not triggering a action
 
 
Q