iOS UITextField输入<后自动追加空格的实现需求及代码问题
Fix UITextField Auto-Space After "<" Input
Got it, let's sort out this issue! Your current code blocks the "<" character entirely, but we need to adjust it so that whenever a user types "<", it automatically adds a space right after while keeping the "<" itself. Here's the step-by-step fix:
Key Changes Needed
- Remove "<" from the restricted characters list since we no longer want to block it
- Detect when the replacement string contains "<"
- Replace any "<" in the input with "< " (the character plus a space)
- Maintain the original maximum length check to avoid overflow
Modified Code
// Remove "<" from restricted characters since we want to allow it now let RESTRICTED_CHARACTERS = "" // Keep other restricted chars here if you need them func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Handle the "<" auto-space logic first var modifiedString = string if modifiedString.contains("<") { // Replace every "<" with "< " to add the trailing space modifiedString = modifiedString.replacingOccurrences(of: "<", with: "< ") } // Keep your original maximum length check let maxLength = maxLenghtOfTextField // Ensure this variable is properly defined let currentString: NSString = textField.text! as NSString let newString: NSString = currentString.replacingCharacters(in: range, with: modifiedString) as NSString // Re-add restricted character check if you need to block other chars let restrictedSet = CharacterSet(charactersIn: RESTRICTED_CHARACTERS) if let _ = modifiedString.rangeOfCharacter(from: restrictedSet) { return false } return newString.length <= maxLength }
How It Works
- When the user types "<", the code immediately replaces it with "< "
- If the user pastes a string with multiple "<" (like "a<b<c"), it converts to "a< b< c"
- The maximum length check ensures the final string doesn't exceed your text field's limit
- You can still retain other restricted characters in
RESTRICTED_CHARACTERSif needed
Example Output
- Typing "<" → Text field shows "< "
- Typing "hello <world" → As you type "<", it becomes "hello < ", then typing "world" gives the desired "hello < world"
内容的提问来源于stack exchange,提问作者Akash Srivastava
相关产品推荐
相关产品推荐

