Last active
November 9, 2020 02:47
-
-
Save mikru1688/532960fa5010c684b5397100f8ce1f87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// onChange事件 | |
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
print("textField.text: \(textField.text!)") | |
print("range: \(range.location)") | |
print("string: \(string)") | |
print("") | |
// 不能輸入空白 | |
if string.isContainsSpaceCharacters() { | |
return false | |
} | |
// 不能輸入中文字 | |
if string.isContainsChineseCharacters() { | |
return false | |
} | |
// 第一個字轉大寫 | |
if range.location == 0 && !string.isContainsPhoneticCharacters() { | |
textField.text = string.substring(from: 0, to: 1).uppercased() + string.substring(from: 1).lowercased() | |
return false | |
} | |
// 是否含有特殊字元 | |
if string.hasSpecialCharacter() { | |
return false | |
} | |
// 長度不得大於等於10 | |
guard let textFieldText = textField.text, | |
// 被取代的字數在 textField 的 range | |
let rangeOfTextToReplace = Range(range, in: textFieldText) else { | |
return false | |
} | |
// 被取代的字 | |
let substringToReplace = textFieldText[rangeOfTextToReplace] | |
// textFieldText.count = textField.count(已存在的字數) - substringToReplace.count(被取代的字數) + string.count(輸入的字數) | |
let count = textFieldText.count - substringToReplace.count + string.count | |
if count <= 10 { | |
return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment