在 iOS 中设置 tableView 内的 editText 长度限制

Set editText length limitation inside tableView in iOS

我使用 tableView 作为注册屏幕,我需要对每一行强制执行一些长度限制。我使用了下面的函数,但它让所有字段都具有相同的约束。有谁知道如何处理它?

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

由于您的文本字段委托方法在单元格中,因此单元格需要知道对其文本字段强制执行的长度。

您的视图控制器需要根据当前索引路径向 cellForRowAt 中的每个单元格提供该长度。

textLength 属性 添加到您的单元格 class,然后根据需要在 cellForRowAt 中设置该值。

然后单元格 class 中的 shouldChangeCharactersIn 可以使用 textLength 属性 而不是硬编码的 12 你现在有。