SwiftUI in ObjectiveC Project - List works in preview, not when it is run

Viewed 482

I have a very big objective-c project and am trying to incorporate SwiftUI slowly. I have been able to successfully implement some screens in swiftUI classes which are called from Objective-c classes.

One strange bug am facing now is that List is not visible when the app is run. It is visible in preview though. And also when I replace List with VStack, it appears fine when the app is run. If I make a standalone SwiftUI app and run this code, then too it runs fine. The issue is only when I call this class from objective-c class.

Attached images

Xcode Preview Screenshot

Device Screenshot

Code


import SwiftUI

struct InfoShareView: View {
    var body: some View {
             List{
                    Text("First Line")
                    Text("Second Line")
            }
            .padding()
            .background(Color.white)
        }

}

struct InfoShareView_Previews: PreviewProvider {
    static var previews: some View {
        InfoShareView()
    }
}

And here is the call to InfoShareView


import UIKit
import SwiftUI

class AboutViewControllerSwift: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let swiftController = UIHostingController(rootView: InfoShareView())
        addChild(swiftController)

        swiftController.view.translatesAutoresizingMaskIntoConstraints  = false
        view.addSubview(swiftController.view)

        swiftController.view.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        swiftController.view.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

     }


}

And here is the call from objective-c class

AboutViewControllerSwift *aboutViewController = [[AboutViewControllerSwift alloc] initWithNibName:nil bundle:nil];
self.nvgController=[[UINavigationController alloc]initWithRootViewController:aboutViewController];
self.window.rootViewController=self.nvgController;
[self.window makeKeyAndVisible];

2 Answers

I think this is due to constraints, try use instead following

    ...
    view.addSubview(swiftController.view)

    swiftController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    swiftController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    swiftController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    swiftController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

Adding this to the last line of viewdidload worked for me:

swiftController.view.frame = self.view.frame
Related