0

I'm trying to create a stackview with dynamic number of lables.

I tried with:

let nValues: String = "A , B, C, D"

if let someArray = nValues.components(separatedBy: ",") {
         let label: UILabel = UILabel()
            for nValue in someArray {
              label.text = nValue
              label.textColor = .black
              nutrientValueLabel?.backgroundColor = .white
              myStackView.addSubview(label)
              print(nValue)
     }
 }

But i get only:

A
B
C
D

and empty stackView. I don't know what is my mistake.

Mr. Geek
  • 21
  • 2
  • 1
    Might be your stack view is not expanding, give your stack view background colour to find that. If that's not the issue then trying using "stackView.addArrangedSubview(label)" instead of addSubView to add label. – Abhishek Aug 12 '19 at 13:24

1 Answers1

1

My mistake was that I created my label at the beginning. I put it in the for loop. And used

myStackView.addArrangedSubview(label)

instead of

myStackView.addSubview(label)

So This is the whole code:

let nValues: String = "A , B, C, D"

if let someArray = nValues.components(separatedBy: ",") {
      for nValue in someArray {
          let label: UILabel = UILabel()
          label.text = nValue
          label.textColor = .black
          nutrientValueLabel?.backgroundColor = .white
          myStackView.addArrangedSubview(label)
     }
 }
Mr. Geek
  • 21
  • 2