我想我对swift中的delegates有一个误解。我想做的是,在我的Controller中以编程方式添加一个textField。因此,我编辑了我的类,如下图所示。
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {
}
在我的理解中,现在我可以添加一个UITextFieldDelegate到我的Textfield中 然后它就会调用扩展。但不知为何,每次我设置委托时,它都会告诉我。
Cannot assign value of type '(HomeController) -> () -> HomeController' to type 'UITextFieldDelegate'?
因此,我想知道,如何将TextField的委托人设置为UITextFieldDelegate?
我的类看起来是这样的。
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {
let sampleTextField: UITextField = {
let textField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
textField.placeholder = "Enter text here"
textField.font = UIFont.systemFont(ofSize: 15)
textField.borderStyle = UITextField.BorderStyle.roundedRect
textField.autocorrectionType = UITextAutocorrectionType.no
textField.keyboardType = UIKeyboardType.default
textField.returnKeyType = UIReturnKeyType.done
textField.clearButtonMode = UITextField.ViewMode.whileEditing
textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
textField.delegate = self
return textField
}()
}
更改。
let sampleTextField: UITextField = {
改为:
lazy var sampleTextField: UITextField = {
编辑...
补充说明一下...
当声明一个属性(类级变量)时,用 var
或 let
它是立即被实例化的,并且对类的其他部分一无所知。
如果你使用 lazy var
的时候,它才会被实例化。首用...... 这时 是否 知道这个班级,它可以访问 self
.