textfielddidbegin 编辑不更新标签

textfielddidbegin editing not updating label

我的 swift 目标下面的代码是当用户在文本字段中输入内容时它会反映在 currentPageLabel 中。我认为会执行此操作的功能无效。我在文本字段中输入的任何内容都不会显示在标签上。我所有的代码都不使用故事板。

var currentPageLabel = UILabel()
var tt = UITextfield()

func textFieldDidBeginEditing(_ textField: UITextField) {
    currentPageLabel.text = tt.text
}

试试这个 UITextFieldDelegate 方法:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    currentPageLabel.text = text
    return true
}

您可以在这种情况下使用 addTarget 功能!只需将目标添加到 viewDidload 方法中的 textField,并添加标有 @objc textFieldDidChange 的选择器方法。在 textFieldDidChange 函数中将文本设置为您的标签!

textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)


@objc func textFieldDidChange(_ textField: UITextField) {
    currentPageLabel.text = textField.text
}