Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the frame of a UIViewController in Swift

I am currently integrating a UIViewController with UIViewControllerRepresentable into my SwiftUI project and would now like to change the frame of the UIViewController.
For that I used this code:

let vc = UIViewController()
vc.view.frame.size = CGSize(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)

However, when I integrate the view created by UIViewControllerRepresentable into my SwiftUI project in a VStack with a list, the UIViewController does not have the size I want.
Look at this

My hole code is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    func makeUIViewController(context: Context) -> UIViewController {
        let vc = UIViewController()
        vc.view.frame.size = CGSize(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)
        vc.view.backgroundColor = .gray
        vc.view.alpha = 0
        
        let bannerView = GADBannerView(adSize: kGADAdSizeBanner)
        bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        bannerView.alpha = 0
        bannerView.rootViewController = vc
        bannerView.delegate = context.coordinator
        bannerView.load(GADRequest())

        vc.view.addSubview(bannerView)
        
        return vc
    }

kGADSizeBanner is a size variable from Google for the ad.

Also, I was wondering why my ad isn’t appearing in the center of the gray UIViewController. Can someone help out?

What I tried so far:

  1. vc.view.translatesAutoresizingMaskIntoConstraints = false
  2. vc.view.frame = CGRect(origin: .zero, size: CGSize(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height))

>Solution :

Override sizeThatFits in your UIViewControllerRepresentable implementation.

For a fixed size, just return the CGSize you want, but you can also try experimenting with taking the proposal into account.

func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: UIViewController, context: Context) -> CGSize? {
    kGADAdSizeBanner.size
}

The banner is not at the centre of the view controller, because it is at (0, 0), a typical default location for a view that you didn’t set a position explicitly or added any constraints.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading