不推荐使用Objective-C选择器的字符串文字;使用'#selector'代替

时间:2016-06-09 23:26:40

标签: ios xcode swift2

我有以下代码:

 override func viewDidLoad() {
            super.viewDidLoad()
            //Looks for single or multiple taps.
            let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
            view.addGestureRecognizer(tap)
            // Do any additional setup after loading the view.
        }

func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

运行应用程序时当错误修复工作发生另一个错误时会发生此错误

4 个答案:

答案 0 :(得分:3)

由于更新了swift语言,您收到此错误,请更改您的点击选择器:

let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))

确保方法dismissKeyboard在同一个视图控制器中,如果它不是你需要做#selector(WhateverHasThatMethod.dismissKeyboard)

另外,请确保dismissKeyboard方法确实存在,它应该是以下内容:

func dismissKeyboard(){
    YourInputField.endEditing(true)
}

答案 1 :(得分:0)

T

答案 2 :(得分:0)

从Swift 2.2开始,请改用: #selector(YourClass.dismissKeyboard)

答案 3 :(得分:0)

除了#selector之外,您还可以从下面的链接中看到Swift 2.2中的一些新变化:

https://swift.org/blog/swift-2-2-new-features/

在Swift 2.2中无效,但在Swift 2.1中无效

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem =
        UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                        action: "addNewFireflyRefernce")
}

func addNewFireflyReference() {
    gratuitousReferences.append("We should start dealing in black-market beagles.")
}

将在Swift 2.2及更高版本中运行

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem =
        UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                        action: #selector(addNewFireflyRefernce))
}

func addNewFireflyReference() {
    gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
}

Swift 3.0即将推出:

https://swift.org/blog/swift-3-0-release-process/