我有一个 tableviewcontroller,我已将其添加为子 ViewController。它的 View 被添加到容器 View (普通 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))
}
当我在添加容器 View 之前添加背景图像时,前几行隐藏在导航栏后面。
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
最佳答案
在ViewController
中设置self.edgesForExtendedLayout = .None
而不是tableViewController.edgesForExtendedLayout
然后它就可以工作了。
因为edgesForExtendedLayout
适用于UIViewController
而不是来自TableViewController
的 View
您可以看到第一个图像,tableview 的灰色位于 navigationBar
下方,因为 contentview 将位于 navigationBar
下方,然后 tableViewController.view 填充内容 View
那为什么拳头会起作用呢?您可以在 Explaining difference between automaticallyAdjustsScrollViewInsets, extendedLayoutIncludesOpaqueBars, edgesForExtendedLayout in iOS7 中查看更多详细信息
希望对你有帮助:-)
关于xcode - 当父 View Controller 有背景时 UITableView 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37611132/