我在我的iOS應用程序中使用Swift語言開發的登錄頁面。 在第一個字母不應該與單/雙空間和用戶輸入文本後,它應該允許單個空間,不允許雙空間,並需要設置文本長度的限制。如何在Swift 3中限制TextField的雙/單空格iOS
我想限制用戶在敲擊單層/雙層空間,同時啓動時間輸入文本,並需要允許單個空格輸入第一個字母文本框後
我能夠做的單/雙的一方,但不按照我的要求工作。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//for double space restrict
if (range.location > 0 && (textField.text?.characters.count)! > 0) {
//Manually replace the space with your own space, programmatically
//Make sure you update the text caret to reflect the programmatic change to the text view
//Tell Cocoa not to insert its space, because you've just inserted your own
return false
}else {
if textField.tag == 1 || textField.tag == 2 { //restrict text length
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLengthForTextField
}
}
return true
}
任何人都可以提出建議。謝謝
你可以添加你現在使用的代碼嗎? –
只需檢查天氣textfield.text最後一個字符是否爲空格。 – soul