2

I am new in swift. I have created dynamic button by pressing another button in the same viewController with following code:

@IBAction func yenibtn(sender: AnyObject) {

    let btn = UIButton()
    btn.frame = CGRectMake(10, 10, 50, 50)  //set frame
    btn.setTitle("btn", forState: .Normal)  //set button title
    btn.setTitleColor(UIColor.redColor(), forState: .Normal) //set button title color
    btn.backgroundColor = UIColor.greenColor() //set button background color
    btn.tag = 1 // set button tag
    btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
    self.view.addSubview(btn) //add button in view



}
func clickMe(sender:UIButton!)
{
    print("Button Clicked")

}

and I created second viewController and navigate by performSegueWithIdentifier function. When i call back the previous controller the dynamic object disappears. Is there a way to retain dynamic button during reload of the previous ViewController?

Hamid Shahsavari
  • 1,151
  • 18
  • 30
Alex Guba
  • 134
  • 1
  • 10

1 Answers1

2

Just use this:

   var btn:UIButton!
@IBAction func yenibtn(sender: AnyObject) {
btn= UIButton()
 btn.frame = CGRectMake(10, 10, 50, 50)  //set frame
///... your code
}

UPDATE

Using your code in the second viewcontroller to close

 @IBAction func basgeri(sender: AnyObject) {

        performSegueWithIdentifier("bir", sender: self)
    }

thinking "I'm closing the viewcontroller", BUT YOU ARE WRONG! You create a new ViewController! You are not returning to the previous one!

To fix it use this:

 @IBAction func basgeri(sender: AnyObject) {

presentingViewController?.dismissViewControllerAnimated(true, completion: nil)

    }
Vyacheslav
  • 23,112
  • 16
  • 96
  • 174