如何使用 UITextField Custom class 将文本字段字符限制为最多 10 个并避免空格?

How to limit textfield characters upto 10 and avoid whitespaces using UITextField Custom class?

如何使用 UITextField Custom 将文本字段字符限制为最多 10 个并避免出现空格 class?

这是我当前的代码。

import UIKit

class PinTextField: UITextField , UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (string == " ") {
            return false
        }
        
        return true
        
    }
       
}

让我们把你的函数修改成这样

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (string == " ") {
        return false
    }
    let currentText = textField.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)

    return (updatedText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).count <= 10)
}

如果您在自定义 class.

中使用委托,请不要忘记在 awakeFromNib 中添加 self.delegate = self

我认为这会对面临同样问题的人有所帮助。