How can l add subviews to my stackView? I try, but l can't see them in my view

561 Views Asked by At

I created class :UIView, where l made a label, textField and stackView. I want to add them to my stackView, but l can't figure out where is the problem.

class View: UIView {

let stackView: UIStackView = {
    let sv = UIStackView()
    sv.axis = .vertical
    sv.distribution = .fillEqually
    sv.spacing = 10
    sv.translatesAutoresizingMaskIntoConstraints = false
    return sv
}()

let errorCodeLabel: UILabel = {
    let lbl = UILabel()
    lbl.text = "Error"
    -------- (code)
    lbl.translatesAutoresizingMaskIntoConstraints = false
    return lbl
}()

let textField: UITextField = {
    let tf = UITextField()
    -------- (code)
    tf.translatesAutoresizingMaskIntoConstraints = false
    return tf
}()

init() {
    super.init(frame: .zero)
    setUpStackView()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setUpStackView() {
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.addArrangedSubview(errorCodeLabel)
    stackView.addArrangedSubview(textField)
}

After this l go to my viewController, make this constant:

let tField = View()

And add some constraints for it.

But when l run my simulator, I don't see anything. Help, please!

1

There are 1 best solutions below

0
On

You need to add the stackView as a subview of the view. In init do addSubview(stackView). Additionally you need to add constraints from the stackView to the parent view.

As a suggestion I’d make your class be a subclass of UIStackView since you’re not adding multiple elements to the view directly anyways.