【问题标题】:How to add a view between table view and navigation bar?如何在表格视图和导航栏之间添加视图?
【发布时间】:2016-11-29 06:31:04
【问题描述】:

所以我想要实现的是我想在表格视图和导航栏之间添加一个视图。层次结构如下: Top-NavigationBar-betweenView-tableView-Bottom.

我试过这样的,但是 betweenView 没有到导航栏下面,并且 tableView 上面有一个奇怪的空白区域。有人知道吗?谢谢!

    let betweenView = searchController.searchBar

    self.view.addSubview(betweenView)

    let upperConstraint = NSLayoutConstraint(item: betweenView, attribute: .top, relatedBy: .equal, toItem: self.tableView, attribute: .top, multiplier: 1, constant: (self.navigationController?.navigationBar.frame.height)!)
    let lowerConstraint = NSLayoutConstraint(item: self.tableView, attribute: .top, relatedBy: .equal, toItem: searchView, attribute: .bottom, multiplier: 1, constant: 0)

    self.view.addConstraint(upperConstraint)
    self.view.addConstraint(lowerConstraint)

【问题讨论】:

  • @Essence of chicken 表格视图标题的问题是它与tableView一起滚动,我希望将betweenView固定在顶部。我实际上正在使用 UIViewController 并已经在其中放置了一个表视图,但是约束的行为不像我想要的那样,这就是我要问的。谢谢你的评论!:D

标签: ios swift uitableview navigationbar


【解决方案1】:

你需要在这里做两件事:

1) 将搜索视图的约束布局到顶部布局指南。这将根据需要将您的搜索视图移动到导航栏下方:

let upperConstraint = NSLayoutConstraint(item: searchView, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0)

2)您需要确保表格不会自动调整滚动到导航控制器:

tableView.automaticallyAdjustsScrollViewInsets = false

【讨论】:

  • 感谢您的回复。我已经尝试过您的解决方案,我已将约束的“toItem”更改为 topLayoutGuide,但由于某种原因,betweenView 仍然隐藏在导航栏之后:(我根本不明白为什么 betweenView 必须坚持屏幕而不是导航栏下方。
  • 您确定在布局指南中使用了 .bottom 属性吗?这是一个示例,您可以将其粘贴到操场上以查看其工作情况:gist.github.com/pixelrevision/6482661045002868cf0ba3ad8ec264a1