UiTextfield-首字母必须为0 [英] UiTextfield- First letter must be 0

查看:104
本文介绍了UiTextfield-首字母必须为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用电话号码texfield,现在我在texfield中使用这种格式(#)### ### ###,现在的问题是我希望将第一个字符0强制性化,例如(0)959 554 545,因此用户输入的任何第一个字符都必须输入0,

I am using phone number texfield, now i am using this format for texfield (#) ### ### ###, now issue is that i want first character 0 as compulsary, like this (0) 959 554 545, so user enter whatever first character must be typed 0,

这是我的代码

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

    let newString = textField.text
    if ((newString == "") && (newString?.count == 0)){
        txtMobileNumber.text = "0"
        return true
    }else if ((newString?.count)! > 0){
        return true
    }
    return false
}

推荐答案

shouldChangeCharactersIn方法中,如果新字符串数大于15,则返回false.否则,请删除(0)并保留空格,然后如果字符串不为空在开头添加(0).然后每3个字符分割一次字符串,并用空格分隔符将所有字符串连接起来.

In shouldChangeCharactersIn method return false if new string count is greater than 15. Else remove (0) and empty spaces, then if the string isn't empty add (0) at the beginning. Then split the string by every 3 characters and join all string with space separator.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 15 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    let newText = String(stride(from: 0, to: oldText.count, by: 3).map {
        let sIndex = String.Index(encodedOffset: $0)
        let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
        return String(oldText[sIndex..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}

这篇关于UiTextfield-首字母必须为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆