这是我为标签添加标签的无尽追求。我唯一能够显示标签的方法是使用框架对其进行初始化。但是,如果这样做,标签将完全忽略我尝试施加的任何约束。
这是xib的代码:
import UIKit
class TestSheet: UIView {
@IBOutlet weak var testStackView: UIStackView!
override init(frame: CGRect) {
super.init(frame: frame)
let subView: UIView = loadViewFromNib()
subView.frame = self.bounds
addSubview(subView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func loadViewFromNib() -> UIView {
let view: UIView = UINib(nibName: "TestSheet", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
return view
}
}
下面,我实例化XIB,创建标签,然后尝试将其居中:
func makeTestPage() {
let testView = UINib(nibName: "TestSheet", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? TestSheet
let centerLabel = UILabel()
//The line below will show a label, but it won't obey constraints:
//let centerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
centerLabel.translatesAutoresizingMaskIntoConstraints = false
centerLabel.text = "Hello middle of the view"
testView?.addSubview(centerLabel)
NSLayoutConstraint.activate([
centerLabel.centerXAnchor.constraint(
equalTo: testView!.centerXAnchor, constant: 0),
centerLabel.centerYAnchor.constraint(
equalTo: testView!.centerYAnchor, constant: 0)
])
pdfPages.append(testView!)
}
这就是什么都没出现的样子...
您忘了为标签说translatesAutoresizingMaskIntoConstraints = false
。当您这样做时,它们的行为会好得多。