[英]No method declared with Objective-C selector ('nextPage')
[英]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)
}
我猜您的问题出在Selector
部分。
在Swift 2.2中,选择器语法已更改,因此您现在可以对选择器进行编译时检查。 您可以在此处阅读更多有关此内容的信息 。
要回答您的问题,请使用以下语法:
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
了button pressed
。
希望对您有帮助。
试试这些
button.addTarget(self, action: #selector(buttonAction), forControlEvents: UIControlEvents.TouchUpInside)
你的方法
func buttonAction (sender:UIButton)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.