Search code examples
iosxcodeswiftsegue

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.


Solution

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

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