2

I want to add and remove the UILabel in the UIStackview. The number of added UILabel will be depend on the length of string(eg. if string is SMITH the it should add 5 UILabel in the UIStackview. As user will click on next button the all 5 UILabel should remove and the next generated UILabel will depend on the next string.

I have created a function which will add the new UILabel to UIStackview, and it is working fine only as user first time on it. But as user will click next button in 2nd time the code i used not removing the old UILabel but still it is adding new UILabel in UIStackview.

@IBAction func btnNext(_ sender: UIButton) {

        removeLabel()
        for i in 0...countArray.count {
            if i == count {
                for j in 1...countArray[i] {
                    label.tag = j
                    text.tag = j
                    createLabel(x: x, y: y, width: width, height: 1)
                    createText(x: x, y: y, width: width, height: 30)
                    x += width + 5
                }
            }
        }
        count += 1
    }


//Mark:- for removing the old UILable
  func removeLabel() {
        label.removeFromSuperview()
    }

Error:- It should remove the old UILabel as user click on next button on 2nd time, it is not removing but it is adding new UILabel based

Result:- It should add the new UILabel based on the string length(character count) and as user will click on next also need to remove old UILabel and add new UILabel again based on the string length(character count)

sham
  • 115
  • 9

1 Answers1

2

Here is how btnNext(_:) should look like,

@IBAction func btnNext(_ sender: UIButton) {
    let str = "SMITH"
    self.stackView.subviews.forEach({ stackView.removeArrangedSubview($0) })
    str.forEach { (char) in
        let label = UILabel()
        label.text = String(char)
        stackView.addArrangedSubview(label)
    }
}

The above code is an example. Try using it with your own code.

PGDev
  • 23,751
  • 6
  • 34
  • 88