字符计数不适用于第二个文本字段

问题描述

我正在构建一个简单的欢迎页面,其中包含姓名和年龄文本输入字段。我能够成功地限制 name 字段上的字符输入计数,但是在 age 字段上使用相同的逻辑根本不起作用。想法?

class WelcomeViewController: UIViewController,UITextFieldDelegate {


@IBOutlet weak var nameTextField: UITextField!

@IBOutlet weak var ageTextField: UITextField!



override func viewDidLoad() {
    super.viewDidLoad()
    
    nameTextField.delegate = self
    ageTextField.delegate = self
    
}


// Character Count Code UITextField
func textField(_ nameTextField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool {
    // get the current text,or use an empty string if that Failed
    let currentText = nameTextField.text ?? ""

    // attempt to read the range they are trying to change,or exit if we can't
    guard let stringRange = Range(range,in: currentText) else { return false }

    // add their new text to the existing text
    let updatedText = currentText.replacingCharacters(in: stringRange,with: string)

    // make sure the result is under # characters
    return updatedText.count <= 30
}

func textField2(_ ageTextField: UITextField,shouldChangeCharactersIn range2: NSRange,replacementString string2: String) -> Bool {
    // get the current text,or use an empty string if that Failed
    let currentText2 = ageTextField.text ?? ""

    // attempt to read the range they are trying to change,or exit if we can't
    guard let stringRange2 = Range(range2,in: currentText2) else { return false }

    // add their new text to the existing text
    let updatedText2 = currentText2.replacingCharacters(in: stringRange2,with: string2)

    // make sure the result is under # characters
    return updatedText2.count <= 2
}

解决方法

委托方法具有系统调用的特定签名 (1em)。您的第一个函数使用该模式。

您的第二个当前没有,因为您将其命名为 s.lines().joinToString(transform = String::trim,separator = "\n") -- 系统没有理由知道调用以该前缀开头的内容。

相反,您可能应该使用单个函数,然后根据发送到第一个参数的 textField(_:shouldChangeCharactersIn:replacementString:) 来让它表现不同:

textField2

这显然可能是一个 UITextField,如果您限制在 2 个文本字段内,甚至可能只是一个 func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool { if textField == nameTextField { //content } if textField == ageTextField { //content } } 。在 else if 块中,您可以调用单独的专用函数,也可以将所有逻辑保留在 else 块中。

if 示例:

if