父视图控件具有背景时的UITableView插图

时间:2016-06-03 09:49:47

标签: xcode swift autolayout

我有一个tableviewcontroller我已经添加为子ViewController。它的视图被添加到containerview(普通UIView)。这很好用,它会自动调整顶部插图:

TableView with correct top inset

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))
    }
}

结果:

TableView with first couple of rows hidden

为什么会这样,我该如何预防?

在Github上测试项目:https://github.com/bvankuik/TestBackgroundLayout

1 个答案:

答案 0 :(得分:1)

self.edgesForExtendedLayout = .None而不是ViewController设置tableViewController.edgesForExtendedLayout,然后就可以了。

因为edgesForExtendedLayout适用于UIViewController,而不适用于TableViewController

你可以看到第一张图片,tableview的greycolor在navigationBar之下,因为contentview将在navigationBar之下,然后tableViewController.view填充内容视图

那么为什么拳头会起作用呢?您可以在Explaining difference between automaticallyAdjustsScrollViewInsets, extendedLayoutIncludesOpaqueBars, edgesForExtendedLayout in iOS7

中查看更多详细信息

希望它有所帮助: - )