Reputation:
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
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:
btn
needs to be declared with let
."buttonAction:"
.viewDidLoad
.buttonAction
method needs to be declared at the top level of your viewController.Upvotes: 1
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