1

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:

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))
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It works! I am so happy 😀.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.