【问题标题】:How to assign textfield or any delegate in Swift Language?如何在 Swift 语言中分配文本字段或任何委托?
【发布时间】:2015-05-14 08:44:35
【问题描述】:

我只是 Swift 语言的新开发者。 我想将文本字段委托分配给视图控制器。我试着这样分配

class LoginViewController: UIViewController <UITextFieldDelegate>

它返回以下错误“无法专门化非泛型类型'UIViewController'”

【问题讨论】:

    标签: swift delegates uitextfield


    【解决方案1】:

    您需要使用逗号添加要符合的协议:

    class LoginViewController: UIViewController, UITextFieldDelegate
    

    您只能从一个类中扩展,但要符合尽可能多的协议:

        class LoginViewController: UIViewController, UITextFieldDelegate, UIAlertViewDelegate
    

    来自Apple doc

    class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
        // class definition goes here
    }
    

    【讨论】:

    • 如果有多个代表怎么办? class LoginViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate 这个方法合适吗?
    • 更新答案:是的,就是这样
    • 太棒了。 +1 寻求快速帮助。
    【解决方案2】:

    请使用逗号添加委托/数据源/协议:

    class MyClass: UIViewController ,UITableViewDelegate, UITableViewDataSource ..
    {...}

    【讨论】:

      【解决方案3】:

      我想补充一点,您可以通过遵守您班级的extension 中的协议来分隔您的代码以提高可读性:

      class DetailViewController: UIViewController {
      
          [your class implementation]
      
      }
      
      extension DetailViewController: UICollectionViewDelegate, UICollectionViewDataSource {
      
          [list of your delegate methods]
      
      }
      

      我个人更喜欢这种方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多