ios 无法将 ViewController 类型的值分配给 UITextFieldDelegate 类型的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29605496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:35:40  来源:igfitidea点击:

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

iosswiftdelegatessyntax-erroruitextfielddelegate

提问by David

Here's the error when I wrote the line self.MessageTextField.delegate = self:

这是我写行时的错误self.MessageTextField.delegate = self

/ChatApp/ViewController.swift:27:42: Cannot assign a value of type 'ViewController' to a value of type 'UITextFieldDelegate?'

/ChatApp/ViewController.swift:27:42:无法将“ViewController”类型的值分配给“UITextFieldDelegate”类型的值?

Here's my Swift code (ViewerController.swift):

这是我的 Swift 代码 (ViewerController.swift):

//
//  ViewController.swift
//  ChatApp
//
//  Created by David Chen on 15/4/12.
//  Copyright (c) 2015年 cwsoft. All rights reserved.
//

import UIKit
import Parse

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var messagesArray:[String] = [String]()

    @IBOutlet weak var MessageTableView: UITableView!
    @IBOutlet weak var ButtonSend: UIButton!
    @IBOutlet weak var DockViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var MessageTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        //
        self.MessageTableView.delegate = self
        self.MessageTableView.dataSource = self
        //Set delegate
        self.MessageTextField.delegate = self

        self.messagesArray.append("Test 1")
        self.messagesArray.append("Test 2")
        self.messagesArray.append("Test 3")
    }

    @IBAction func ButtonSendPressed(sender: UIButton) {
        self.view.layoutIfNeeded()
        UIView.animateWithDuration(0.5, animations: {
            self.DockViewHeightConstraint.constant = 400
            self.view.layoutIfNeeded()
            }, completion: nil)
    }

    //MARK : TextField Delegage Methods


    //MARK : Table View Delegate Methods

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.MessageTableView.dequeueReusableCellWithIdentifier("MessageCell") as! UITableViewCell
        cell.textLabel?.text = self.messagesArray[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messagesArray.count
    }
}

回答by luk2302

The line self.MessageTextField.delegate = selfcauses the error since you try to assign selfas the delegateof a UITextField.
But your ViewControlleris nota UITextFieldDelegate. To make your class this kind of delegte, you need to adopt the UITextFieldDelegateprotocol. 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

该行self.MessageTextField.delegate = self会导致错误,因为您尝试将其分配selfdelegatea UITextField
但是,你ViewController是不是一个UITextFieldDelegate。为了让你的班级成为这种委托,你需要采用UITextFieldDelegate协议。这可以通过将它添加到您的类继承/符合的协议和类列表中来实现。在您的情况下,这是通过更改行来完成的

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

to

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate

回答by keithbhunter

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

声明您的类符合UITextFieldDelegate协议并实现您需要的任何协议方法。

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

回答by Honey

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 CustomViewControllerto conform to the UITableViewDelegate, UITableViewDataSourceprotocols.

我确实扩展了我CustomViewController的协议以符合UITableViewDelegate,UITableViewDataSource协议。

The reason was that selfisn't accessible if you're using let. I had to lazy var customerCardTableView: UITableViewi.e.:

原因是self如果您使用let. 我不得不说lazy var customerCardTableView: UITableView

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...

lets 需要在实例化期间发生,但lazy vars 可以延迟到实例化后的某个时间,因此它们可以访问self...

回答by mylogon

Embarrassing to own up to it, but worth a mention. Make sure that you're extending the correct view controllerwhen 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.

如果您使用自动完成功能,这很容易做到,因为乍一看,它看起来是一样的。