我有一个如下的子视图控制器。
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)
}
}
现在问题是我在图像视图的父视图控制器中有一个奇怪的边距问题。如下面的屏幕快照所示,图像视图隐藏在导航栏的后面。如果我将子视图控制器作为根视图控制器并加载应用程序,则图像视图将正确定位。如何解决这个问题?
答案 0 :(得分:1)
您既不给子视图一个框架,也不给它一个约束
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