Lynxbci
Lynxbci

Reputation: 71

Delete buttons previously added

I add 24 buttons using a Class at the start of my app and the user can press any or all of them. Then 'another' button has been pressed I would like to remove all of these 24 buttons.

Adding them:

for j in 0...2 {
    for i in 0...7 {
        // use the CLASS KSPIckButton to format the buttons
        let buttonOne: UIButton = KSPickButton(frame: CGRect(x: (j + 1) * 28 + (j * 80), y: (i + ii) * 35 + buttonSet, width: 110, height: 30))
            
        // Add the button to the storyboard
        self.view.addSubview(buttonOne)
        
    }
}

How can I delete them?

I would like to just have a simple loop through all 24 buttons using self.view.Remove() but cannot work out how?

Upvotes: 0

Views: 35

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100549

Solution 1

Add a tag

self.buttonOne.tag = 333
self.view.addSubview(buttonOne)

Then

self.view.subviews.forEach { 
   if $0.tag == 333 {  
      $0.removeFromSuperview() 
   } 
}

Solution 2

You can also add them to an array and loop over them with calling removeFromSuperview

Solution 3

self.view.subviews.forEach { 
   if $0 is KSPickButton {  
      $0.removeFromSuperview() 
   } 
}

Upvotes: 3

Related Questions