ios - 如何阻止用户不在 UITextView iOS 中的文本开头键入空格?

标签 ios swift uitextfield uitextview

我想在 iOS 的文本字段开头限制空格键的使用。我尝试使用以下逻辑,但它不允许单词之间的任何位置有空格。在这种情况下请帮助我。

if self.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) != nil {
    return false
}
return true

最佳答案

对于 TextField

swift 5.2、Xcode 11.4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard range.location == 0 else {
        return true
    }

    let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) as NSString
    return newString.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines).location != 0
}

关于ios - 如何阻止用户不在 UITextView iOS 中的文本开头键入空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805534/

相关文章:

ios - UIWebView 不会在 Swift 中重新加载新的 URL

ios - Xcode 5 : Multiple test targets in one scheme: "Simulator already in use"

ios - 为什么我的日期解析器在 Swift 中不起作用?

ios - Firebase 数据未显示在 TableView 中

ios - 部分屏幕截图和图像质量损失

ios - UITextField 数字键盘 : dot instead of comma for float values

ios - dyld : Library not loaded Reason: no suitable image found. 是否找到:/private/var/mobile/Containers/Bundle/Application…

swift - TableViewCell Nib 错误 : loaded the nib but the view outlet was not set

ios - 高级自动完成 Swift

ios - Reactive Cocoa - 以编程方式设置文本时,不会调用 UITextView 的 rac_textSignal