You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. When the user types "<", the code immediately replaces it with "< "
  2. If the user pastes a string with multiple "<" (like "a<b<c"), it converts to "a< b< c"
  3. The maximum length check ensures the final string doesn't exceed your text field's limit
  4. You can still retain other restricted characters in RESTRICTED_CHARACTERS if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:16:25