ios - 如何在 Swift 3 iOS 中限制 TextField 的双/单空格

标签 ios swift xcode

我的 iOS 应用程序中有登录页面,它是用 Swift 语言开发的。 在第一个字母中不应使用单/双空格,并且在用户输入文本后应允许单空格,不允许双空格并且需要设置文本长度限制。

我想限制用户在开始输入文本时点击单/双空格,并且在文本字段中输入第一个字母后需要允许单空格

我可以做单人/双人中的任何一个,但没有按照我的要求工作。

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 
}

谁能给点建议。谢谢

最佳答案

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let rawString = string
     let range = rawString.rangeOfCharacter(from: .whitespaces)
    if ((textField.text?.characters.count)! == 0 && range  != nil)
    || ((textField.text?.characters.count)! > 0 && textField.text?.characters.last  == " " && range != nil)  {
        return false
    }
return true
}

关于ios - 如何在 Swift 3 iOS 中限制 TextField 的双/单空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543141/

相关文章:

ios - iOS 默认使用脏区域吗?

iphone - 调整大小并裁剪图像居中

ios - 无法单击 GMaps for iOS subview 上的文本字段

ios - 面向协议(protocol)的编程示例在 swift 3.0 中不起作用

ios - Xcode 在控制台中显示构建输出

ios - Xcode 4.6.x 和 Xcode 5 可以共享项目目录吗?

ios - Swift - 将核心数据检索到自定义单元格

ios - 同时对 2 个或更多位置进行地理编码

ios - MapView 不要求位置权限

objective-c - GUI 元素对属性的变化没有反应