子视图控制器和边距

Child View Controller and Margin

我有一个子视图控制器,如下所示。

import UIKit
class SampleChildViewController : UIViewController {

    let imageView : UIImageView = {
        let imageview = UIImageView()
        imageview.translatesAutoresizingMaskIntoConstraints = false
        imageview.clipsToBounds = true
        imageview.contentMode = .scaleAspectFit
        imageview.image = UIImage(named: "cat")
        return imageview
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageView)

        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
            imageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 8),
            imageView.widthAnchor.constraint(equalToConstant: 150),
            imageView.heightAnchor.constraint(equalToConstant: 150)
            ])
    }


}

然后我有如下所示的父视图控制器。我已将子视图控制器添加到父视图控制器中,如下所示。

import UIKit

class ViewController: UIViewController {

    let child : SampleChildViewController = SampleChildViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        child.view.translatesAutoresizingMaskIntoConstraints = false
        addChild(child)
        view.addSubview(child.imageView)
        child.didMove(toParent: self)

    }


}

现在的问题是我在图像视图的父视图控制器中有一个奇怪的边距问题。正如您在下面的屏幕截图中看到的,图像视图隐藏在导航栏后面。如果我将子视图控制器作为根视图控制器并加载应用程序,则图像视图会正确定位。这个问题怎么解决?

你既不给子视图框架也不给约束

child.view.translatesAutoresizingMaskIntoConstraints = false 

另外你应该添加视图而不是 imageView

view.addSubview(child.view) 
NSLayoutConstraint.activate([
   child.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
   child.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 8),
   child.view.leftAnchor.constraint(equalTo: view.leftAnchor),
   child.view.rightAnchor.constraint(equalTo: view.rightAnchor),
])

并设置

navigationController?.navigationBar.prefersLargeTitles = false