这是我向xib中的堆栈视图添加标签的不懈追求。我唯一能够显示标签的方法是使用框架对其进行初始化。我知道标签具有固有的大小,应该足够了,但是由于某些原因,如果我仅使用var testLabel = UILabel()
初始化标签,它将不会出现。当我创建带有框架的标签时,问题在于它完全忽略了堆栈视图设置。设置(x:0,y:0)将其放置在堆栈视图的右上角。如果我添加了第二个标签,它也将在x,y设置所指示的位置移动,而无需考虑堆栈视图设置。
这是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 labelOne = UILabel(frame: CGRect(x: 0, y: 500, width: 300, height: 20))
labelOne.font = labelOne.font.withSize(20)
labelOne.textColor = .blue
labelOne.text = "Leonardo"
//I've tried with and without the constraints below
labelOne.heightAnchor.constraint(equalToConstant: 20).isActive = true
labelOne.widthAnchor.constraint(equalToConstant: 100).isActive = true
let labelTwo = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 20))
labelTwo.font = labelOne.font.withSize(40)
labelTwo.textColor = .green
labelTwo.text = "Raphael"
testView?.testStackView.addArrangedSubview(labelOne)
testView?.testStackView.addArrangedSubview(labelTwo)
pdfPages.append(testView!)
}
您忘了为标签说translatesAutoresizingMaskIntoConstraints = false
。当您这样做时,它们的行为会好得多。