Xcode 7 swift, ''no method declared with objective-c selector (function)" warning

时间:2016-09-01 06:06:40

标签: ios swift xcode7

I want to add an action to a button, but I heard that the code below does not work. Does anyone know the way to add an action to a button.

button.addTarget(self, action: Selector("function:"), forControlEvents: .TouchUpInside)

Here is the code I am using Xcode 7.3.1

override func viewDidLoad() {
super.viewDidLoad()

let button = UIButton(frame: CGRectMake(100, 80, 30, 30))

func pressed(sender: UIButton!) {

print("button pressed")

}

button.backgroundColor = UIColor.redColor()

button.addTarget(self, action: #selector(pressed(_:)), forControlEvents: .TouchUpInside)

self.view.addSubview(button)

}

2 个答案:

答案 0 :(得分:4)

I'm guessing that your problem is with the Selector part.

In Swift 2.2 the selector syntax was changed so you now get a compile time check for your selectors. You can read more about that here.

To answer your question, this syntax:

button.addTarget(self, action: #selector(function(_:)), forControlEvents: .TouchUpInside)

should make you and - more importantly in this case (sorry :)) - the compiler happy.

Update (after looking at the code you provided)

You need to move the pressed function outside of your viewDidLoad function so that it is a separate function.

So your code ends up looking like this:

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(frame: CGRectMake(100, 80, 30, 30))
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: #selector(pressed(_:)), forControlEvents: .TouchUpInside)
    self.view.addSubview(button)
}

func pressed(sender: UIButton) { //As ozgur says, ditch the !, it is not needed here :)
    print("button pressed")
}

And that seems to work, I can see button pressed in my console now at least.

Hope that helps you.

答案 1 :(得分:0)

Try These

button.addTarget(self, action: #selector(buttonAction), forControlEvents: UIControlEvents.TouchUpInside)

your method

func buttonAction (sender:UIButton)
{
}