user2389087 user2389087 - 2 years ago 103
Swift Question

How to remove multiple buttons that I created with a loop?


1) I initiate the button above the class :

var myButton = UIButton()

2) 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)



3) 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



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] {

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

Answer Source


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))



3) To remove buttons:

for btn in buttonsArray {


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download