带有第一个字母的UitextFiled必须为0,格式为(0)1234 56789 [英] UitextFiled with first letter must 0 and format will be like (0) 1234 56789

查看:57
本文介绍了带有第一个字母的UitextFiled必须为0,格式为(0)1234 56789的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用电话号码texfield,现在我在texfield(#)#### #####中使用这种格式,现在的问题是我希望将第一个字符0设为强制性字符,例如(0)1234 56789 ,因此用户输入的任何第一个字符必须输入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) 1234 56789, so user enter whatever first character must be typed 0, its not duplicate quesion number format is different

这是我的代码,但是不起作用

here is my code but its not working

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
}

推荐答案

在此格式(#) #### #####中,仅使用两个空格.因此,您可以在没有这样的for循环的情况下在特定索引处插入空间

In this format (#) #### ##### only two spaces are used. So you can insert space at a particular index without a for loop like this

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 > 14 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    if oldText.count > 3 { 
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 3))
    }
    if oldText.count > 8 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 8))
    }
    textField.text = oldText
    return false
}

这篇关于带有第一个字母的UitextFiled必须为0,格式为(0)1234 56789的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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