首页 > 解决方案 > 字符数在第二个文本字段上不起作用

问题描述

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

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
}

标签: iosswiftxcodetextfield

解决方案


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

您的第二个目前没有,因为您已经命名了它textField2- 系统没有理由知道调用以该前缀开头的东西。

相反,您可能应该使用单个函数,然后根据UITextField发送到第一个参数的函数使其行为不同:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == nameTextField {
      //content
    }
    if textField == ageTextField {
      //content
    }
}

这显然可能是一个else if,或者甚至只是一个,else如果你限制在 2 个文本字段。在if块中,您可以调用单独的专用函数,或者将所有逻辑保留在if块中。

示例switch

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    switch textfield {
    case nameTextField:
      //content
    case ageTextField:
      //content
    default:
      return true
    }
}

推荐阅读