uzair
uzair

Reputation: 766

Swift - Add and Remove UILabel on button tap

I've created two buttons, One button to create a UILabel and other to delete the created UILabel.

On tapping Button1, I'm running a for-loop, to create four(4) UILabels and I'm able to do that.

On tapping Button2, I want to delete all the UILabels that I created with Button1.

Sidenote: I don't want to hide the UILabels as the variable 'noOfLabels' can be increased from 4 to 15 or any other number as per requirement.

Here is what I've tried.

class ViewController: UIViewController {
   var myLabel : UILabel!
   var noOfLabels = 4
    @IBAction func addButton(_ sender: Any) {

    if(myLabel != nil && !myLabel.isHidden)
    {
        myLabel.removeFromSuperview()
    }
    print("AddLabel button is Tapped")
    var yval = 0
    for i in 0...noOfLabels
    {
        myLabel = UILabel()
        myLabel.frame =  CGRect(x: 30, y: 200 + yval, width: 90, height: 50)
        myLabel.text = "Hello \(i)"
        view.addSubview(myLabel)
        yval += 80
    }
}

@IBAction func removeButton(_ sender: Any) {

    print("Remove button is Tapped")
    myLabel.removeFromSuperview()

}
override func viewDidLoad() {
    super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

With the above code, I'm able to remove just one label.

I need help removing all UILabel on tapping Button2

Upvotes: 1

Views: 1826

Answers (2)

Robert Dresler
Robert Dresler

Reputation: 11150

This happens because you have reference just for last created instance of label and you remove just this one. You need array of labels in order to be able to remove all created labels.

var labels = [UILabel]()

then when you need to create new label, also append it to this array

@IBAction func addButton(_ sender: Any) {

    labels.forEach { $0.removeFromSuperview() }
    labels.removeAll()

    for i in 0...noOfLabels {
        let newLabel = UILabel(frame: CGRect(x: 30, y: 200 + (i * 80), width: 90, height: 50)) // <--- new instance
        newLabel.text = "Hello \(i)"
        view.addSubview(newLabel)
        labels.append(newLabel) // <--- appending to an array
    }
}

Then when you need to remove all labels from their superview, just iterate through the labels array

@IBAction func removeButton(_ sender: Any) {
    labels.forEach { $0.removeFromSuperview() }
    labels.removeAll()
}

Upvotes: 2

define

var labelList: [Label] = []

in

addButton(_ sender: Any) {
...
view.addSubview(myLabel)
labelList.append(myLabel)
...
}


@IBAction func removeButton(_ sender: Any) {

print("Remove button is Tapped")
for i in 0...noOfLabels
{
    labelList[i].removeFromSuperview()

}
labelList = []

Upvotes: 0

Related Questions