Reputation: 1945
My goal is to add labels to a stackview in a xib. Everything below works great if the results are being displayed using a view controller. But I don't need to display the view I'm creating. I just want to add it to an array. (The array will be converted to a PDF later.) For some reason, if I just save the view, anything in the stack view will not appear when the PDF is created. My actual xib has many other fields that show up just fine. It's only the fields I try to programmatically add as labels to a stack view that fail to appear!
This is my xib. The stack view is pinned to the edges and it's set to fill equally.
And this is the code for the xib. There's one outlet for the view and one for the stack view.
import UIKit
class ContainerView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var testStackView: UIStackView!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
Bundle.main.loadNibNamed("ContainerView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
}
}
And finally, here is the class that adds labels to the stack view. It has been simplified considerably.
import UIKit
class PreparePDF : UIView {
func addMyArrangedSubviews (
let containerView = ContainerView()
let testLabel1 = UILabel()
testLabel1.text = "Hola"
testLabel1.backgroundColor = .red
let testLabel2 = UILabel()
testLabel2.text = "Hello"
testLabel2.backgroundColor = .yellow
containerView.testStackView.addArrangedSubview(testLabel1)
containerView.testStackView.addArrangedSubview(testLabel2)
pdfPages.append(containerView)
}
I've tried to ask this question several times, but I think I was making it sound too complicated. I'm not sure this is any better!
Upvotes: 0
Views: 939
Reputation: 16327
You are creating a view with: let containerView = ContainerView()
, then you are adding labels to its stackView, then you hit the end of the function and containerView
is deinit
ed because you did not retain it or add it as a subview.
Your init for ContainerView is also wrong. if you call init it will not load the nib file. You should call UINib.instantiate(withOwner:options:)
instead and move your setup code to awakeFromNib
and fatalError the constructors
so no-one tries to make the nib programmatically and bypass the nib file (in which case the outlets would not be connected).
let containerView = UINib(nibName: String(describing: ContainerView.self), bundle: nil)
.instantiate(withOwner: nil, options: nil).first as! ContainerView
Upvotes: 1