【问题标题】:pin UiTableView to (view controller)view with layout anchor使用布局锚将 UiTableView 固定到(视图控制器)视图
【发布时间】:2016-09-30 02:21:13
【问题描述】:

我想将一个表视图“固定”到它的容器,即视图控制器的视图。由于 UIView 没有锚属性,我尝试使用 layoutMarginsGuide 来完成。

UIView 不提供布局边距属性的锚属性。相反, layoutMarginsGuide 属性提供了一个 UILayoutGuide 对象来表示这些边距。使用指南的锚属性来创建您的约束。

        let margins = self.view.layoutMarginsGuide
    self.tableView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
    self.tableView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true

但是运行这段代码我得到以下错误:

** Terminating app due to uncaught exception 'NSGenericException', reason:   'Unable to activate constraint with items <UITableView: 0x7fdfd0ab5e00; frame = (0 0; 768 1024); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7fdfd8452e00>; layer = <CALayer: 0x7fdfd84c11c0>; contentOffset: {0, 0}; contentSize: {0, 0}> and <UILayoutGuide: 0x7fdfd86d7ca0 - "UIViewLayoutMarginsGuide", layoutFrame = {{0, 0}, {0, 0}}, owningView = <UIView: 0x7fdfd75a8aa0; frame = (0 0; 768 1024); autoresize = W+H; layer = <CALayer: 0x7fdfd0409270>>> because they have no common ancestor.  Does the constraint reference items in different view hierarchies?  That's illegal.'

重要的部分:

    ...because they have no common ancestor.  Does the constraint reference items in different view hierarchies?  That's illegal.'

但这应该如何工作?

【问题讨论】:

  • iOS 9 模拟器上没有此类问题。

标签: ios swift autolayout ios9 nslayoutanchor


【解决方案1】:

首先将约束更改为这样 self.tableView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true self.tableView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true

如果问题仍然存在,请确保将 tableview 添加为 view 的子视图

view.addSubview(tableView)

【讨论】:

  • 非常感谢!我确实在分​​配约束之后添加了 tableView
猜你喜欢
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 2015-02-06
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多