限制两个特定文本字段中的字符数

Limit the number of characters in two specific textfields

我正在尝试限制两个特定文本字段中的字符数(总共有四个)。我能够为一个文本字段成功执行此操作,但不能同时为两个文本字段执行此操作。两者的最大字符限制应为 36。谁能帮我这个?以下是我到目前为止所拥有的。注意:我是一个新手程序员,所以如果这个问题有一个明显的答案,请原谅我。谢谢

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let maxLength = 36
    let currentString: NSString = (fullNameTextField.text ?? "") as NSString
    
    let currentString2: NSString = (occupationTextField.text ?? "") as NSString
    
    let newString: NSString =
        currentString.replacingCharacters(in: range, with: string) as NSString
    return newString.length <= maxLength
}

不要从 fullNameTextFieldoccupationTextField 获取文本,而是使用 textField 参数。

但是如果你只想限制 fullNameTextFieldoccupationTextField 中的字符数,请添加一个 if 语句。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    /// check the textField
    if textField == fullNameTextField || textField == occupationTextField {
        let maxLength = 36
        let currentString: NSString = (textField.text ?? "") as NSString
        let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
        return newString.length <= maxLength
    }
    
    /// don't limit characters if textField is NOT `fullNameTextField` or `occupationTextField`
    return true
}