简体   繁体   中英

Dynamically generate button and remove all button generate when next button is click

I want to dynamically create buttons over a for loop. When the loop runs let say it runs 3 time I want to create 3 buttons and when that is done, when I click next button it should remove those buttons and create new ones base on how much times it loops. Thats my problem and i have been trying for days no luck can someone help me please or the best solution to the problem thanks in advances. I was also viewing this post Remove UIButton Programmatically in swift but i still wasn't able to accomplish this. Please see below my code:

func createButton(){

    let button = UIButton()

     button.frame = CGRect(x: 15, y: buttonY, width: 200, height: 30)
     buttonY = self.buttonY + 50
     button.setTitle("Button", for: UIControlState.normal)
     button.layer.cornerRadius = 10
     button.backgroundColor = UIColor.blue
     button.backgroundColor = .green
     button.addTarget(self, action: #selector(buttonAction), for: UIControlEvents.touchUpInside)
     view.addSubview(button)

     //buton.removeFromSuperview()
}

@objc func buttonAction(sender: UIButton!) {
     print("Button tapped: ")
 }

@IBAction func nextButton(_ sender: Any) {

   test(value: "remove")
}



func generateButton(){
 for i in 1...3{
  createButton()
 }

}

func generateButton(){
 for i in 1...3{
  createButton()
 }

}

This is one method but there are others depending on how you are using the buttons.

First you need to keep references to the buttons you create so that you can remove them later so in your class add an instance variable like this:

var buttonList: [UIButton] = []

Then change your createButton method to return the button it has created like this:

func createButton() -> UIButton {

    let button = UIButton()

     button.frame = CGRect(x: 15, y: buttonY, width: 200, height: 30)
     buttonY = self.buttonY + 50
     button.setTitle("Button", for: UIControlState.normal)
     button.layer.cornerRadius = 10
     button.backgroundColor = UIColor.blue
     button.backgroundColor = .green
     button.addTarget(self, action: #selector(buttonAction), for: UIControlEvents.touchUpInside)
     view.addSubview(button)

    return button
}

Then you can have these functions to generate the buttons and remove the buttons and call them as needed:

func generateButtons() {
    for loop in 0..<3 {
        self.buttonList.append(self.createButton())
    }
}

func removeButtons() {
    for button in self.buttonList {
        button.removeFromSuperview()
    }
    self.buttonList.removeAll()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM