swift - 如何为标签添加约束?

标签 swift xcode constraints anchor

所以我创建了一个数组并将其放入 UILabel 中,现在我希望这个标签贴在顶部。但是通过网络搜索这就是我所能想到的:

let currentWeek = Date()

let weekDays = UILabel.init()
weekDays.frame = CGRect(x: 10, y: 65, width: 414, height: 25)
weekDays.text = "\(currentWeek.day())"
self.view.addSubview(weekDays)
weekDays.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
weekDays.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
weekDays.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
weekDays.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

根据一些指南,这组约束应该使我的标签拉伸(stretch)以填满整个屏幕。 但即使我没有收到任何错误警告,它也没有改变我标签的外观。

最佳答案

weekDaystranslatesAutoresizingMaskIntoConstraints设为false,即

weekDays.translatesAutoresizingMaskIntoConstraints = false

A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.

By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.

并将 height constraint 添加到 weekDays 而不是 bottomAnchor,即。

weekDays.heightAnchor.constraint(equalToConstant: 100.0)

关于swift - 如何为标签添加约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810620/

相关文章:

iphone - Objective C 数组元素都以相同的值结束

ios - 如何将 UIImageView 放置在 Storyboard 中另一个 View 的一半

constraints - Jacop,约束求解器

ios - UILabel隐藏文本问题

python - 如何正确设置带有约束和多个最优值的 scipy.optimize 最小化?

ios - Core Data + Swift + 加载模型不起作用

swift - 如何根据全局变量决定显示哪个 View

ios - 返回 CGValues 导致 Xcode 错误

ios - 在 Metal 中渲染后翻转图片

ios - 是否可以在 swift 2.2 中禁用除选定行之外的 tableviewCell 行滑动功能?