Xcode 7 swift,“没有使用 objective-c 选择器(函数)声明的方法”警告

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

我想给按钮添加一个动作,但我听说下面的代码不起作用。有谁知道给按钮添加动作的方法吗

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

这是代码 我正在使用 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)

}

试试这些

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

你的方法

func buttonAction (sender:UIButton)
{
}

我猜你的问题出在 Selector 部分。

在 Swift 2.2 中,选择器语法已更改,因此您现在可以对选择器进行编译时检查。您可以阅读更多相关信息 here

要回答您的问题,语法如下:

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

应该让你和 - 在这种情况下更重要的是(抱歉 :)) - 编译器快乐。

更新(查看您提供的代码后)

您需要将 pressed 函数移到 viewDidLoad 函数之外,使其成为一个单独的函数。

所以你的代码最终看起来像这样:

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

这似乎有效,我现在至少可以在我的控制台中看到 button pressed

希望对你有所帮助。