Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign a value of type ViewController to a value of type UITextFieldDelegate?

The line self.MessageTextField.delegate = self causes the error since you try to assign self as the delegate of a UITextField.
But your ViewController is not a UITextFieldDelegate. To make your class this kind of delegte, you need to adopt the UITextFieldDelegate protocol. This can be achieved by adding it to the list of protocols and classes your class inherits from / conforms to. In your case that is done by changing the line

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

to

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate

Declare that your class conforms to the UITextFieldDelegate protocol and implement any of those protocol methods that you need.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { ... }

I had the same problem, but it was because of a different issue:

class CustomViewController: UIViewController {

    let customerCardTableView: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        table.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
        table.delegate = self
        table.dataSource = self
        table.separatorStyle = .none
        table.separatorColor = UIColor(rgb:0xFFFFFF)
        table.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

        return table
    }()

    ...other code 
}

and I did extend my CustomViewController to conform to the UITableViewDelegate, UITableViewDataSource protocols.

The reason was that self isn't accessible if you're using let. I had to lazy var customerCardTableView: UITableView i.e.:

lazy var customerCardTableView: UITableView = {
    let table = UITableView()
    table.translatesAutoresizingMaskIntoConstraints = false
    table.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
    table.delegate = self
    table.dataSource = self
    table.separatorStyle = .none
    table.separatorColor = UIColor(rgb:0xFFFFFF)
    table.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

    return table
}()

lets are required to happen during instantiation, but lazy vars can be delayed to a time after instantiation, hence they can access self...


Embarrassing to own up to it, but worth a mention. Make sure that you're extending the correct view controller when declaring conformance. For example, don't do this by accident.

class ViewController: UIViewController {

}

extension SimilarlyNamedViewController: UITableViewDelegate {

}

It's an easy one to do if you use autocomplete and gets by you because, at a glance, it looks the same.