【发布时间】:2021-12-03 01:29:11
【问题描述】:
我在 Swift 中以编程方式为标签设置约束时遇到问题。我希望标签填满整个屏幕。但我不知道该怎么做。
感谢您的帮助。
【问题讨论】:
我在 Swift 中以编程方式为标签设置约束时遇到问题。我希望标签填满整个屏幕。但我不知道该怎么做。
感谢您的帮助。
【问题讨论】:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.text = "Hello"
label.backgroundColor = UIColor.yellow
self.view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
let width: NSLayoutConstraint
width = label.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1)
let top: NSLayoutConstraint
top = label.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
let bottom: NSLayoutConstraint
bottom = label.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
width.isActive = true
bottom.isActive = true
top.isActive = true
}
}
【讨论】:
您可以将此扩展程序用于所有视图
extension UIView {
public func alignAllEdgesWithSuperview() {
guard let superview = self.superview else {
fatalError("add \(self) to a superview first.")
}
self.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
self.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
self.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
self.topAnchor.constraint(equalTo: superview.topAnchor),
self.bottomAnchor.constraint(equalTo: superview.bottomAnchor)
]
NSLayoutConstraint.activate(constraints)
}
}
及用法
view.addSubview(someView)
someView.alignAllEdgesWithSuperview()
【讨论】: