如何在Swift 3 iOS中限制TextField的双/单空间

时间:2017-08-07 09:05:32

标签: 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 
}

任何人都可以提出建议。感谢

9 个答案:

答案 0 :(得分:1)

试试这个

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let result = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
    let text = result as String
    if (text.range(of: "^(?i)(?![ ])(?!.*[ ]{2})[A-Z. ]*$", options: .regularExpression) != nil) {

        return true
    }
    return false
}

如果您需要限制总长度,请将^(?i)(?![ ])(?!.*[ ]{2})[A-Z. ]{1,10}$字符的正则表达式更新为10。根据需要更新长度。

答案 1 :(得分:1)

试用此代码:

    LinearLayout def = (LinearLayout) findViewById(R.id.defense);
    loopViews(def);

它不会允许用户在第一个字母给出空格。例如,如果您需要为//TextField Validation func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if(textField == UserNameText) { if range.location == 0 && string == " " { return false } return true } else if(textField == PasswordText) { if range.location == 0 && string == " " { return false } return true } else { return true } } 字段设置限制,其限制为10个字符表示使用此代码:

username

答案 2 :(得分:0)

请检查此代码。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let trimmedString = textField.text?.trimmingCharacters(in: .whitespaces)
    if (trimmedString.length == 0)
        return false

    //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
        if string.range(of:" ") != nil {
            return false
        }
        return true
    }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
}

限制textfield length的代码应该与标记为1&amp;的textfields一样正常。 2。

答案 3 :(得分:0)

有效!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="upload" id="upload" />
<button type="button" id="showpath">Show me path to file</button>

答案 4 :(得分:0)

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
}

答案 5 :(得分:0)

我最终找到了答案

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    //for double space restrict
    let str = textField.text
    if str?.characters.count == 0 && string == " " {
        return false
    } else if (str?.characters.count)! > 0 {
        if str?.characters.last == " " && string == " " {
            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 
}

答案 6 :(得分:0)

func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if range.location == 0 && string == " " {
       return false
   } else if range.location > 1 && textField.text?.characters.last == " " && string == " " {
       return false
   }else{
       return true
   }
}

嗨,Anli请试试这个会解决你的问题。

答案 7 :(得分:0)

Swift 4.1

使用单行代码就很简单,您可以停止空格

对于所有文本字段

{% for name, table in all_tables %}
    {% if name %}
        <H3>{{ name }}</H3>
        {% render_table table %}
        <br/>
    {% endif %}
{% endfor %}

对于单个文本字段

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
        return true
    }

答案 8 :(得分:0)

斯威夫特 5.0

仅允许 textField 文本中的单个空格与错误处理:

func textField(textField: UITextField, 
               shouldChangeCharactersInRange 
               range: NSRange, replacementString string: String) -> Bool {
    let (isValid, errorMessage) =  validateSpacesInTextChange(newText: string, existingText: textField.text!, in: NSRange) 
    return isValid
}

func validateSpacesInTextChange(newText: String,
                                existingText: String,
                                in range: NSRange) -> (Bool, errorMessage: String?) {
     let range = newText.rangeOfCharacter(from: .whitespaces)
        
     let textNotStartWithSpace = !(existingText.isEmpty && range != nil)
     guard textNotStartWithSpace else { return (false, "Space not allowed at the Begning") }
        
     let notContainTwoSpaces = !(!existingText.isEmpty && existingText.last == " " && range != nil)
     guard notContainTwoSpaces else { return (false, "Only single space allowed") }
        
     return (true, nil)
}