首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用NSLayoutConstraint在容器中以编程方式居中显示表尾视图?

如何使用NSLayoutConstraint在容器中以编程方式居中显示表尾视图?
EN

Stack Overflow用户
提问于 2018-07-02 04:31:25
回答 1查看 218关注 0票数 0

我正在为一个有收藏的应用程序构建一个屏幕。此屏幕将显示用户收藏的项目列表。这个列表将以表视图的形式显示,非常简单。

我正在尝试为列表的空状态添加一些代码,但还没有添加收藏夹。我想在tableFooter中放置一个UIView,然后在该视图的中心放置一个UILabel。我希望视图占据屏幕内的所有可用空间。

到目前为止,我得到的是:

self.tableView.tableFooterView = buildTableViewFooter()

非常不言自明。

func buildTableViewFooter() -> UIView {
  let footer = UIView(frame: self.tableView.frame)
  let label = UILabel()
  label.text = "Use the heart icon to add favorites"
  label.font = UIFont.italicSystemFont(ofSize: 21.0)
  label.textColor = UIColor.lightGray
  label.textAlignment = .center
  label.numberOfLines = 0
  let centerHorizontalConstraint = NSLayoutConstraint(
      item: label,
      attribute: .centerX,
      relatedBy: .equal,
      toItem: footer,
      attribute: .centerX,
      multiplier: 1,
      constant: 0
  )
  footer.addSubview(label)
  footer.addConstraints([
      centerHorizontalConstraint,
  ])
  return footer
}

当我运行应用程序时,我可以判断出我的方法正在触发,视图正在成功创建。但是,我在屏幕上的任何地方都看不到文本。LayoutConstraints引擎试图提供帮助,但我不太确定它试图告诉我什么:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x60400028a9b0 h=--& v=--& UILabel:0x7fa8565417d0'Use the heart icon to add...'.midX == 0   (active)>",
    "<NSLayoutConstraint:0x604000290f90 UILabel:0x7fa8565417d0'Use the heart icon to add...'.centerX == UIView:0x7fa856514e60.centerX   (active)>",
    "<NSAutoresizingMaskLayoutConstraint:0x6040002931f0 h=--& v=--& 'UIView-Encapsulated-Layout-Left' UIView:0x7fa856514e60.minX == 0   (active, names: '|':UITableView:0x7fa857889a00 )>",
    "<NSLayoutConstraint:0x60400028a2d0 'UIView-Encapsulated-Layout-Width' UIView:0x7fa856514e60.width == 375   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x604000290f90 UILabel:0x7fa8565417d0'Use the heart icon to add...'.centerX == UIView:0x7fa856514e60.centerX   (active)>

非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-02 04:42:58

您还需要添加y约束,如

let topConstraint = NSLayoutConstraint(
  item: label,
  attribute: .top,
  relatedBy: .equal,
  toItem: footer,
  attribute: .top,
  multiplier: 1,
  constant: 10
)

并为标签设置此属性

label.translatesAutoresizingMaskIntoConstraints = false
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51126799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档