我有一个tableviewcontroller我已经添加为子ViewController。它的视图被添加到containerview(普通UIView)。这很好用,它会自动调整顶部插图:
override func viewDidLoad() {
super.viewDidLoad()
self.title = "ViewController"
// self.addBackground()
// Set up container for the tableview
self.containerView = UIView()
self.containerView.translatesAutoresizingMaskIntoConstraints = false
self.containerView.backgroundColor = UIColor.greenColor()
self.view.addSubview(self.containerView)
let viewDict = ["container": self.containerView]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[container(100)]", options: [], metrics: nil, views: viewDict))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[container]|", options: [], metrics: nil, views: viewDict))
// Add tableview controller as child
tableViewController = TableViewController()
tableViewController.view.translatesAutoresizingMaskIntoConstraints = false
self.addChildViewController(tableViewController)
self.containerView.addSubview(tableViewController.view)
tableViewController.didMoveToParentViewController(self)
// Layout
let tableViewDict = ["child": tableViewController.view]
self.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[child]|", options: [], metrics: nil, views: tableViewDict))
self.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[child]|", options: [], metrics: nil, views: tableViewDict))
}
当我添加背景图像时,在添加容器视图之前,前几行隐藏在导航栏后面。
private func addBackground() {
let backgroundImage = UIImage(named: "hexley_fork_450")
let backgroundImageView = UIImageView(image: backgroundImage)
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(backgroundImageView)
let viewDict = ["backgroundImageView": backgroundImageView]
let layouts = [
"H:[backgroundImageView]|",
"V:[backgroundImageView]|",
]
for layout in layouts {
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(layout, options: [], metrics: nil, views: viewDict))
}
}
结果:
为什么会这样,我该如何预防?
在Github上测试项目:https://github.com/bvankuik/TestBackgroundLayout
答案 0 :(得分:1)
在self.edgesForExtendedLayout = .None
而不是ViewController
设置tableViewController.edgesForExtendedLayout
,然后就可以了。
因为edgesForExtendedLayout
适用于UIViewController
,而不适用于TableViewController
你可以看到第一张图片,tableview的greycolor在navigationBar
之下,因为contentview将在navigationBar
之下,然后tableViewController.view填充内容视图
希望它有所帮助: - )