0

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.

2 Answers 2

1

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.

            }

}

Sign up to request clarification or add additional context in comments.

Comments

0

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!")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.