编程UIButton在Swift 4 Xcode 9 Beta 6中不起作用,无法添加目标

Oli*_*er 13 selector uibutton addtarget swift4 xcode9-beta

在过去,我以编程方式创建UIButton没有问题,但自从我使用Xcode 9和Swift 4以来,我找不到让这个错误消失的方法.

//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)")
}
Run Code Online (Sandbox Code Playgroud)

错误消息:'NSInvalidArgumentException',原因:' - [Playing.MainMenuViewController pressButton:]:无法识别的选择器发送到实例0x10440a6b0'

OOP*_*Per 22

两点.

首先,自从Swift 2.2(与一年多前发布的Xcode 7.3捆绑在一起)以来,推荐选择符表示法#selector(...).使用表示法,您可能会获得比使用其他表示法更有用的诊断消息.

(您不应忽略使用推荐设置显示的任何警告.)

Seconde,在Swift 4中,你需要显式地注释通过选择器调用的方法@objc.(在非常有限的情况下,Swift隐式应用符号,但不是很多.)

因此,您显示的代码应为:

//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)")
}
Run Code Online (Sandbox Code Playgroud)

这并不重要,但你应该更好地遵循Swift的简单编码规则 - 只有类型名称是大写的.

更好的重命名PositionStartButton,StartButton而且ScrollView,如果你认为你可能有另一个机会公开展示你的代码.