无法在 Swift 中的 UITextFieldDelegate class 初始化程序中使用 TextField

Can't use TextField in UITextFieldDelegate class initializer in Swift

我有一个 enum,我在 class 中用作 UITextFieldDelegate

枚举:

enum Position {
//Enum for Position variable in MemeTextDelegate

case Top, Bottom
init () {   //set outside of enum to .Bottom if needed
    self = .Top
}

UITextFieldDelegate Class:

class MemeTextDelegate: NSObject, UITextFieldDelegate {

    var position = Position()
    var userEnteredText = false //Default value

    override init () {
        switch (position) {
        case (.Top):
            textField.text = "TOP"
        default:
            textField.text = "BOTTOM"
        }
    }

    //Methods removed for this example...
}

ViewController 中,我设置了每个 TextField 的委托,因此它知道它是 'Top' 或 'Bottom'

@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!

let topTextFieldDelegate = MemeTextDelegate()
let bottomTextFieldDelegate = MemeTextDelegate()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //Set Delegates
    self.topTextField.delegate = self.topTextFieldDelegate
    self.bottomTextField.delegate = self.bottomTextFieldDelegate

    //Set individual fields delegate properties for TOP and BOTTOM
    self.topTextFieldDelegate.position = .Top
    self.bottomTextFieldDelegate.position = .Bottom
}

MemeTextDelegate 中带有 textField.text 的每一行都会得到一个编译器错误,内容为:"Use of unresolved identifier 'textField'",而在方法中使用 textField 完全没有问题。

我确信我遗漏了一些基本的东西,所以任何输入都会有所帮助。

根据您提供的代码,MemeTextDelegate 不拥有 textField 的实例。据推测,它只会来自委托方法。但是,您在 init 方法中引用了它。