设置委托时出现无效选择器错误:Xcode 10 swift 4

Invalid selector error on setting delegate: Xcode 10 swift 4

应用程序在我设置 TextField 委托的行崩溃:

listNameTextField = self

viewDidLoad方法中

给出错误

'NSInvalidArgumentException', reason: '-[UIView setDelegate:]: unrecognized selector sent to instance

我已经尝试使 listNameTextField 变量 strong 超过 weak 参考,但它并没有改变问题

import UIKit

class CreateListViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var listNameTextField: UITextField!
    var listNameString: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Create List"
        listNameTextField.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func submitListName(_ sender: UIButton) {
        if listNameString != "" {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "ListView")
            self.present(controller, animated: true, completion: nil)
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textField.resignFirstResponder()
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {

        if let text = listNameTextField.text {
            listNameString = text
        }
    }
}

根据您的错误,您的 listNameTextField 只是 UIView
检查 xib/storyboard.

中的连接

您不能将故事板中 UIView 的类型更改为 UITextField,因为故事板会在 xml 中为 UITextField 生成额外的属性。

您需要从故事板中删除原来的 UIView 并添加新的 UITextField 并建立新的连接。