4

I created a Button programmatically in Swift with this code:

    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. How can I fix this?

Pat Myron
  • 4,437
  • 2
  • 20
  • 39

2 Answers2

2

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

button.addTarget(self, action: "segueToCreate:", forControlEvents: UIControlEvents.TouchUpInside)
Imran
  • 2,985
  • 19
  • 33
  • Swift can infer the `UIControlEvents`, so it can be written more succinctly as `forControlEvents: .TouchUpInside`. – vacawama Oct 04 '15 at 04:53
1

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)
Caleb
  • 124,013
  • 19
  • 183
  • 272