在Swift 4 Xcode 9 Beta 6中无法对UIButton进行编程,无法添加目标 [英] Programming a UIButton is not working in Swift 4 Xcode 9 Beta 6, Cannot add target
问题描述
过去,我可以通过编程方式创建UIButton没问题,但是自从我一直在使用Xcode 9和Swift 4以来,我一直找不到解决这个错误的方法.
In the past I had no problem creating a UIButton programmatically, but ever since I've been using Xcode 9 and Swift 4, I cannot find a way to make this error go away.
//Adding target to UIButton
func PositionStartButton(xOffset: Float){
StartButton.frame = CGRect(x: Int(0 - 40 + xOffset), y: 0, width: 80, height: 80)
StartButton.setImage(#imageLiteral(resourceName: "Logo_Final_WHITE_Face"), for: .normal)
StartButton.addTarget(self, action: "pressButton:", for: .touchUpInside)
ScrollView.addSubview(StartButton)
}
//The target function
func pressButton(_ sender: UIButton){
print("\(sender)")
}
错误消息:"NSInvalidArgumentException",原因:-[Playing.MainMenuViewController pressButton:]:无法识别的选择器已发送到实例0x10440a6b0"
Error Message: 'NSInvalidArgumentException', reason: '-[Playing.MainMenuViewController pressButton:]: unrecognized selector sent to instance 0x10440a6b0'
推荐答案
两点.
首先,由于Swift 2.2(与一年多以前发布的Xcode 7.3捆绑在一起),推荐的选择器表示法为#selector(...)
.与使用其他表示法相比,使用该表示法可能会获得更多有用的诊断消息.
First, since Swift 2.2 (bundled with Xcode 7.3, released more than a year ago), recommended selector notation is #selector(...)
. With using the notation, you may get more useful diagnostic messages, than using other notation.
(您不应忽略使用建议设置显示的任何警告.)
(You should not ignore any warnings displayed with recommended settings.)
第二,在Swift 4中,您需要使用@objc
显式注释通过选择器调用的方法. (在极少数情况下,Swift会隐式地应用该表示法,但数量并不多.)
Seconde, in Swift 4, you need to explicitly annotate methods invoked through selector with @objc
. (In very limited cases, Swift implicitly applies the notation, but not many.)
因此,您显示的代码应为:
So, your code shown should be:
//Adding target to UIButton
func PositionStartButton(xOffset: Float){
StartButton.frame = CGRect(x: Int(0 - 40 + xOffset), y: 0, width: 80, height: 80)
StartButton.setImage(#imageLiteral(resourceName: "Logo_Final_WHITE_Face"), for: .normal)
StartButton.addTarget(self, action: #selector(self.pressButton(_:)), for: .touchUpInside) //<- use `#selector(...)`
ScrollView.addSubview(StartButton)
}
//The target function
@objc func pressButton(_ sender: UIButton){ //<- needs `@objc`
print("\(sender)")
}
这并不重要,但是您最好遵循Swift的简单编码规则-仅将类型名大写.
This is not critical, but you should better follow a simple coding rule of Swift -- only type names are capitalized.
如果您认为您可能还有另一次公开展示代码的机会,最好重命名您的PositionStartButton
,StartButton
和ScrollView
.
Better rename your PositionStartButton
, StartButton
and ScrollView
, if you think you may have another chance to show your code publicly.
这篇关于在Swift 4 Xcode 9 Beta 6中无法对UIButton进行编程,无法添加目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!