user5698241
user5698241

Reputation:

Problems With Swift UIButtons

I have read, and tried many different ways for creating a UIButton, in Xcode 7. However, none of them have worked. Below is one of the codes I have tried, but I get an error "expected declaration," and I can't figure out what is missing. I am new to this and do not totally understand this yet! Thank you!

 btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
    btn.backgroundColor = UIColor.redColor()
    btn.setTtitle("Click me",, forState: UIViewControlState.Normal)
    btn.addTarget(self, action: "button action:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(buttonPuzzle)
    func buttonAction(sender: UIButton!) {
        let btnsendtag: UIButton = sender
        if btnsendtag.tag == 1 {
            print("It worked!")

        } else {
            print("It didn't work")
        }

Upvotes: 0

Views: 75

Answers (2)

vacawama
vacawama

Reputation: 154593

There were a number of typos and inconsistencies in your code. Here is a corrected version that works:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let btn = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
        btn.tag = 1
        btn.backgroundColor = UIColor.redColor()
        btn.setTitle("Click me", forState: .Normal)
        btn.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        self.view.addSubview(btn)
    }

    func buttonAction(sender: UIButton) {
        if sender.tag == 1 {
            print("It worked!")
        } else {
            print("It didn't work")
        }
    }

}

Key points:

  1. btn needs to be declared with let.
  2. Action name is "buttonAction:".
  3. The button creation code needs to be inside a method, usually viewDidLoad.
  4. The buttonAction method needs to be declared at the top level of your viewController.

Upvotes: 1

Bell App Lab
Bell App Lab

Reputation: 818

Your action should be buttonAction:, which is the name of the function you're trying to call.

Also, try marking your function with @objc, so it's visible to UIKit:

@objc func buttonAction(sender: UIButton) { 
    //do something
}

The reason this might work is that UIButton, under the hood, calls respondsToSelector: and performSector: on your object. Swift classes that do not inherit from NSObject directly don't have an implementation for respondsToSelector: and therefore your function doesn't get called.

Upvotes: 0

Related Questions