Swift - 使用 AVMakeRect 在 UIScreen 的中心获取子视图控制器

问题描述

我将一个 vc 作为孩子添加到另一个 vc。我需要使用 AVMakeRect 设置孩子的大小,使其小于屏幕但仍保持其比例。问题是孩子没有居中,它要么离屏幕很远,就好像孩子的中心在屏幕顶部,要么太低了。根据我是使用 UIScreen.main.bounds.w/h / 2 还是 CGPoint(x: UIScreen.main.bounds.midX,y: UIScreen.main.bounds.midY)

,我得到不同的结果

使用 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
    }
}

解决方法

这是我使用 Anchors 和主窗口使 vc 居中的唯一方法。我更愿意使用 CGRect 但 ...

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
}