user2389087 user2389087 - 6 months ago 14
Swift Question

Remove multiple buttons from View with removefromSuper view

I initiate the button above the class

var myButton = UIButton()


I then create x amount of buttons depending on how many items are in an array

for letter in arrayOfLetters {


myButton = UIButton(frame: CGRect(x: buttonX, y: 500, width: someFloat, height: someFloat))
buttonX = buttonX + thirdFloat //spacing


myButton.layer.cornerRadius = 5
myButton.backgroundColor = UIColor.darkGrayColor()
myButton.setTitle("\(letter)", forState: UIControlState.Normal)
myButton.titleLabel?.text = "\(letter)"
myButton.addTarget(self, action: "myButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(myButton)



}


later on once the user has pressed the correct buttons, I call a function to refresh and I want to remove all buttons. This is so I can generate new buttons based on new array

myButton.removeFromSuperview()


However this does nothing, I tried giving the buttons a tag and deleting buttons by tag == tagId but nothing happened.

I can delete all views but it deletes everything else,

I tried this but again nothing happends

var buttons = [myButton]
for button in buttons as! [UIButton] {
button.removeFromSuperview()
}


I want to delete all buttons I added and i'm either not deleting them or deleting everything in the view

Answer

EASY FIX:

1) Inside Class, out of any func:

var buttonsArray = [UIButton]()

2) Declare myButton here and add the append line:

for letter in arrayOfLetters {


     var myButton = UIButton(frame: CGRect(x: buttonX, y: 500, width:     someFloat, height: someFloat))

...

     self.buttonsArray.append(myButton)
}

3) To remove buttons:

for btn in buttonsArray {
    btn.removeFromSuperview()
}

EXPLANATION:

Always store in an array the elements you create with a loop if you want to easily remove all of them at once.