Swift无法识别的选择器已发送到实例

时间:2018-08-13 19:37:01

标签: ios swift uibutton

我正在观看此视频教程https://www.youtube.com/watch?v=H9NhYx9xIiU&t=838s,该视频教程在14:00见,由于未捕获的异常'NSInvalidArgumentException'无法识别的选择器已发送到实例,导致此崩溃终止应用程序。这是代码

func setUpViews(){
    addSubview(titleLabel)
    addSubview(createButton)

    createButton.addTarget(self, action: "createNotice", for: .touchUpInside)

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-4-[v1]-4-|", options: NSLayoutFormatOptions(),
                                                  metrics: nil, views: ["v0": titleLabel, "v1": createButton]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-4-[v0]-4-|", options: NSLayoutFormatOptions(),
                                                  metrics: nil, views: ["v0": titleLabel]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-4-[v0]-4-|", options: NSLayoutFormatOptions(),
                                                  metrics: nil, views: ["v0": createButton]))
}

func createNotice(){
    print("tapped");
}

我尝试了很多来自stackoverflow的解决方案,例如

createButton.addTarget(self, action: "createNotice:", for: .touchUpInside)// adding semicolon 

func createNotice(_ sender: UIButton){
    print("tapped");
}

但问题未解决。

1 个答案:

答案 0 :(得分:2)

代替这个

createButton.addTarget(self, action: "createNotice:", for: .touchUpInside)// adding semicolon 

使用

createButton.addTarget(self, action: #selector(createNotice(_:)), for: .touchUpInside)// adding semicolon 

//

@objc func createNotice(_ sender: UIButton){
  print("tapped")
}