Pat Myron
Pat Myron

Reputation: 4648

How to segue when a new programmatically created button is pressed?

I created a Button programmatically in Swift:

    let image = UIImage(named: "pin") as UIImage?
    let button = UIButton();
    button.setTitle("Add", forState: .Normal)
    button.setTitleColor(UIColor.blueColor(), forState: .Normal)
    button.setImage(image, forState: .Normal)
    button.frame = CGRectMake(15, -50, 200, 38)
    button.center = CGPointMake(190.0, 345.0);// for center
    self.view.addSubview(button)

I have a separate function to try to use my segue with identifier segueOnPin:

 @IBAction func segueToCreate(sender: UIButton) {
    // do something
    performSegueWithIdentifier("segueOnPin", sender: nil)
}

However, I believe the new UIbutton is not properly connected to the second function because it is not working. I usually connect it on the StoryBoard. However, the new button is not on the StoryBoard because it is being programmatically created.

Upvotes: 3

Views: 543

Answers (2)

Caleb
Caleb

Reputation: 125007

However, the new button is not on the StoryBoard because it is being programmatically created. How can I fix this?

You need to set the button's action, like this:

button.addTarget(self, action: "segueToCreate:", forControlEvents: UIControlEvents.TouchUpInside)

Upvotes: 1

Imran
Imran

Reputation: 2941

You never set the target for the button. Add following line in your code.

button.addTarget(self, action: "segueToCreate:", forControlEvents: UIControlEvents.TouchUpInside)

Upvotes: 2

Related Questions