为什么让我的视图的框架 return 全屏,即使视图已通过 safeArea 约束运行?

Why does getting my view's frame return the full screen, even tho the view has been run through the safeArea constraints?

在展示我的 GameScene 之前,我将 safeAreaLayoutGuide 应用到初始视图屏幕 (下面的代码来自 GameViewController).

如果在我调用 之前的任何时候 view.presentScene(scene) 我尝试获取视图的框架,我得到一个空集。

如果我得到框架,呈现场景后,我得到全屏的矩形,即使视图确实出现在 safeAreaLayoutGuide 中。

如何获取视图的安全调整屏幕坐标? 我应该注意我这样做是为了我可以对我的 GameScene 应用适当的约束,因为我只能找到如何为 UIView 做这件事。

class GameViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView?{
        let screenWidthInPoints = UIScreen.main.bounds.width
        let screenHeightInPoints = UIScreen.main.bounds.height

        let imageView = UIView()
        imageView.backgroundColor = .red
        view.addSubview(imageView)

        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        imageView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
        imageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor , constant: -0).isActive = true



        let scene = GameScene(size: CGSize(width: screenWidthInPoints,
        height: screenHeightInPoints))
        scene.backgroundColor = .black
        scene.scaleMode = .aspectFit
        view.presentScene(scene)
        var myRect = view.frame

UIScreen.main.bounds代表整个屏幕,而不仅仅是安全区域。您将必须创建一个单独的视图,将其限制为安全区域插图以获得正确的安全区域大小。在您的情况下,您已经将 imageView 放置在安全区域内。尝试在添加约束后打印出它的大小并在 DispatchQueue.main.async 内执行以确保它仅在当前 pass 布局完成后才被调用。

    let imageView = UIView()
    imageView.backgroundColor = .red
    view.addSubview(imageView)
    
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
    imageView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
    imageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor , constant: -0).isActive = true
    
    
    DispatchQueue.main.async {
        print("imageView.frame: ", imageView.frame)
        
        let scene = GameScene(size: CGSize(width: imageView.frame.width,
                                           height: imageView.frame.height))
        scene.backgroundColor = .black
        scene.scaleMode = .aspectFit
        view.presentScene(scene)
    }