我正在努力强制用户输入仅使用英语,因此如果用户注册,则阻止用户注册其他语言 我不知道firebase是否已经阻止了那些看到后面的用户,但如果他们没有这样做,代码中是否有任何编程方式,或者这在开发应用程序时并不是一个真正的问题我只是吓坏了
func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textFieldToChange == username {
let characterSetNotAllowed = CharacterSet.whitespaces
if let _ = string.rangeOfCharacter(from:NSCharacterSet.uppercaseLetters) {
return false
}
if let _ = string.rangeOfCharacter(from: characterSetNotAllowed, options: .caseInsensitive) {
return false
} else {
return true
}
}
return true
}
答案 0 :(得分:0)
您可以开始对UITextField进行子类化并添加目标以编辑已更改的UIControlEvents并过滤用户在更改时输入的字符串:
class EnglishLettersField: UITextField {
override func willMove(toSuperview newSuperview: UIView?) {
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
editingChanged(self)
}
@objc func editingChanged(_ textField: UITextField) {
guard let text = textField.text?.englishLetters else { return }
textField.text = text
}
}
extension CharacterSet {
// create your own set with the allowed characters to filter your string
static let englishLetters = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ")
}
extension String {
// create a computed property to separate the original text using the custom character set inverted, join it again and return it
var englishLetters: String {
return components(separatedBy: CharacterSet.englishLetters.inverted).joined()
}
}
您可以以编程方式将其添加到视图中或使用界面构建器
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let englishLettersField = EnglishLettersField(frame: CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 200, height: 50)))
view.addSubview(englishLettersField)
}
}