Swift -Get Child View Controller in Center of UIScreen using AVMakeRect

380 Views Asked by At

I add a vc as a child to another vc. I need the size of the child to get set using AVMakeRect so that it is smaller than the screen but still keeps its proportions. The problem is the child isn't centered, it goes either to far up off of the screen, as if the child's center is at the top of the screen, or it's too low. I get different results depending on if I use UIScreen.main.bounds.w/h / 2 or CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)

example results using vc.view.center = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY):

enter image description here

let vc = SomeVC()

var didSubviewsLayout = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if !didSubviewsLayout {
        didSubviewsLayout = true
    
        addChild(vc)
        view.addSubview(vc.view)
        vc.didMove(toParent: self)
    
        let screenWidth = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
    
        let horizontalPadding: CGFloat = 50
    
        let paddedWidth = screenWidth - horizontalPadding
    
        let insideRect = CGRect(x: 0, y: 0, width: paddedWidth, height: screenHeight) // also tried CGFloat.infinity
        let avRect = AVMakeRect(aspectRatio: CGSize(width: 9, height: 16), insideRect: insideRect)
                
        vc.view.frame.size.width = avRect.size.width
        vc.view.frame.size.height = avRect.size.height
        vc.view.center = CGPoint(x: screenWidth / 2, y: screenHeight / 2) // also tried CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)

        // vc.view.layoutIfNeeded() // same results with or without calling it
    }
}
1

There are 1 best solutions below

0
On

This is the only way that I got the vc to center using Anchors and the main window. I'd much rather use CGRect but ...

if !didSubviewsLayout {
    didSubviewsLayout = true

    guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }

    addChild(vc)
    view.addSubview(vc.view)
    vc.didMove(toParent: self)

    let screenWidth = UIScreen.main.bounds.width

    let horizontalPadding: CGFloat = 50

    let paddedWidth = screenWidth - horizontalPadding

    let insideRect = CGRect(x: 0, y: 0, width: paddedWidth, height: .infinity)
    let avRect = AVMakeRect(aspectRatio: CGSize(width: 9, height: 16), insideRect: insideRect)
            
    vc.view.translatesAutoresizingMaskIntoConstraints = false
        
    vc.view.widthAnchor.constraint(equalToConstant: avRect.size.width).isActive = true
    vc.view.heightAnchor.constraint(equalToConstant: avRect.size.height).isActive = true

    // I use the window's Y and X here
    vc.view.centerYAnchor.constraint(equalTo: window.centerYAnchor).isActive = true
    vc.view.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
}