所以我创建了一个数组并将其放入 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)以填满整个屏幕。 但即使我没有收到任何错误警告,它也没有改变我标签的外观。
最佳答案
将weekDays
的translatesAutoresizingMaskIntoConstraints
设为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/