ios - 如何使用 NSLayoutConstraint 以编程方式在容器中居中表格页脚视图?
问题描述
我正在为一个有收藏夹的应用程序构建一个屏幕。此屏幕将显示用户收藏的项目列表。这个列表将显示在一个表格视图中,非常普通的东西。
当尚未添加收藏夹时,我正在尝试为列表的空状态添加一些代码。我想把 aUIView
放在那个视图的中心,tableFooter
然后把 aUILabel
放在那个视图的中心。我希望视图占据屏幕内的所有可用空间。
到目前为止,这就是我所拥有的:
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)>
非常感谢!
解决方案
您还需要添加 y 约束,例如
let topConstraint = NSLayoutConstraint(
item: label,
attribute: .top,
relatedBy: .equal,
toItem: footer,
attribute: .top,
multiplier: 1,
constant: 10
)
并将其设置为标签
label.translatesAutoresizingMaskIntoConstraints = false
推荐阅读
- r - ggplot2,在 Y 轴上不需要的命名
- react-native - 不支持 crypto.getRandomValues()
- android - setSharedElementReturnTransition 不起作用
- visual-studio - 构建一个简单的 Hello World 会出现错误 MSB8040
- java - 更改 RecyclerView Android Java 中显示的 ArrayList
- python - 基于字符串输入扩展和简化表达式
- java - 当我输入参数时如何解决我的意图
- docker - 如何在不停机的情况下`docker-compose up --build`?
- android-studio - 怎样才能自动加载存储在内存中的必要地图?
- c# - 解析 JSON 返回异常