Skiddyflyer
Skiddyflyer

Reputation: 213

Adding Button programmatically

Is there any way to programmatically add a button that will run an action when its clicked? What code would be used?

I am new to swift and the new languages, I am used to just adding a button in the storyboard and running an IBAction from there.

Upvotes: 0

Views: 234

Answers (2)

Oxcug
Oxcug

Reputation: 6604

The other answer uses SpriteKit, if you're not using it, this is how you would do it:

In your UIViewController subclass:

func whateverFuncYouWantLikeViewDidLoad() {
     let button = UIButton(frame: CGRect(x: <#x#>, y: <#y#>, width: <#w#>, height: <#h#>)
     button.addTarget(self, "someSelector", .TouchUpInside)
     addSubview(button)
}

func someSelector() {
     println("that tickles!")
}

Upvotes: 0

Bill peek
Bill peek

Reputation: 120

You can use a SPSprintNode as your button and activate it in the touches function. Or you can use a button class to do the work for you. If your using ObjectiveC, there are some great button class examples on Github. If your using Swift they are a little harder to find. The third and last option is you can use a label and then tell touches to call the button function. Here is an example:

     var button = SKSpriteNode(imageNamed: "button.png")
    button.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.5)//center
    button.alpha = 1.0//optional
    addChild(button)

Then in your Touches Begin put this:

        for touch in touches {
        let touchLocation = touch.locationInNode(self)
            if (CGRectContainsPoint(button.frame, touchLocation)) {
                button.alpha = 0.5//optional
               //call function to perform something here.

            }

}

Upvotes: 1

Related Questions