大家好!)需要一些幫助!)
如何允許用戶在具有某些規則的 TextField 中僅輸入一個句子(單詞或字符)?)
用戶必須只輸入這個詞:
Qwerty
然后文本欄位必須自動顯示連字符:
Qwerty-
之后,用戶只能在文本欄位中輸入以下數字:
12345
預期的結果必須只有這樣:
Qwerty-12345
每個字母或數字的輸入順序非常重要!)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = onlyCharTextField.text else { return true }
if textField == onlyCharTextField {
let allowedCharacters = "Q-w-e-r-t-y "
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let allowedDigits = "1-2-3-4-5"
let allowedDigitSet = CharacterSet(charactersIn: allowedDigits)
if text == "Qwerty" {
onlyCharTextField.text = "Qwerty" "-"
}
let typedCharacterSet = CharacterSet(charactersIn: string)
let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet) || allowedDigitSet.isSuperset(of: typedCharacterSet)
return alphabet
} else {
return false
}
}
我很困惑..((你有什么想法如何實作這個嗎?)謝謝你的每一個回答!)
uj5u.com熱心網友回復:
沒那么復雜。您可以使用“首先計算新文本是什么”模式,然后檢查“Qwerty-12345”是否以該文本開頭。這是因為如果以正確的順序輸入文本,則文本始終是“Qwerty-12345”開頭的一部分(或全部):
Q
Qw
Qwe
Qwer
Qwert
Qwerty-
Qwerty-1
Qwerty-12
Qwerty-123
Qwerty-1234
Qwerty-12345
一個特殊情況是文本是Qwerty. 這是您不允許鍵盤更改文本,而是以編程方式將其更改為Qwerty-.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
if newText == "Qwerty" {
textField.text = "Qwerty-"
return false
}
return "Qwerty-12345".starts(with: newText)
}
請注意,這仍然允許用戶洗掉他們已經輸入的內容,但只能從末尾開始,并Qwerty-12345從洗掉的點輸入。如果你想禁止這樣做,你可以檢查replacementString引數是否為空,這表示洗掉:
if string.isEmpty {
return false
}
這不會禁用粘貼。如果需要,請參閱如何在 Swift 中禁用 TextField 中的粘貼?
uj5u.com熱心網友回復:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let expectedText = "Qwerty-12345" //Text u want user to enter
let halfText = "Qwerty" //special case where u enter an additional -
let enteredText = "\(textField.text ?? "")\(string)" //get the text user has entered
if enteredText == expectedText.prefix(enteredText.count){ //check if the user entered text matches to the the first part of your string
// if it matches change the text of the text field
if enteredText == halfText{
textField.text = "\(enteredText)-" //special case where u add an -
}
else{
textField.text = enteredText
}
}
return false
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/507555.html
下一篇:單擊框并更改框顏色
