如何格式化土耳其电话格式的Textfiled.text?

时间:2015-08-21 13:20:04

标签: ios swift uitextfield

我有一个只需要电话号码的left join,我正在尝试将其格式化为土耳其格式编号,如下所示(555)555 5555.如何在Swift中制作?

3 个答案:

答案 0 :(得分:1)

如果我们假设所有土耳其数字都是10位数字,我们可以按照以下方式进行。

首先让我们定义一个辅助函数来获取子串:

func sub(str: String, start: Int, end: Int) -> String {
    return str.substringWithRange(Range<String.Index>(start: advance(str.startIndex, start), end: advance(str.startIndex, end)))
}

现在我们只应用函数来获取数字的部分:

// Lets say this is the number we get from the textfield
let number = "1234567890"

let start = sub(number, 0, 3) // "123"
let mid = sub(number, 3, 6) // "456"
let end = sub(number, 6, 10) // "7890"

然后我们根据需要将其格式化为单个字符串。

let formatNumber = "(\(start)) \(mid) \(end)" // "(123) 456 7890"

请注意,这仅适用于有10位数字的数字(我怀疑所有土耳其数字都是)。您需要通过指定上面start midend的不同子字符串来修改此格式以设置不同长度的数字。

如果您希望将用户限制为仅使用10位数字,则应在textfield上执行验证。

答案 1 :(得分:1)

您可以在EiditingChange方法上执行此类操作,这会在用户输入文本时将前三个条目更改为此()格式,如果用户正在删除条目,您可以按照相同的方法删除格式

 @IBAction func onEditingChanged(sender: UITextField!)
    {
        var string = sender.text as NSString
        if string.length > 3
        {
            let range = string.rangeOfString("(")
            if range.location == NSNotFound
            {
                var firstPart = string.substringToIndex(3)
                var secondPart = string.substringFromIndex(3)
                var string = "(\(firstPart))\(secondPart)"
                sender.text = string
            }
        }
    }

答案 2 :(得分:0)

var shouldAttemptFormat: Bool = true

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

    if textField == self.phoneNumberTextField{
        let resultString: String = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString:string)
        let oldString: String = self.phoneNumberTextField.text
        let oldCount = count(oldString)
        let newCount = count(resultString)
        shouldAttemptFormat = newCount > oldCount
        return true//newCount < 15
    }else{
        return true
    }
        // otherwise we should just let them continue
}

// MARK: - phone number formatting

func formatPhoneNumber() {
    // this value is determined when textField shouldChangeCharactersInRange is called on a phone
    // number cell - if a user is deleting characters we don't want to try to format it, otherwise
    // using the current logic below certain deletions will have no effect
    if !shouldAttemptFormat {
        return
    }

    // here we are leveraging some of the objective-c NSString functions to help parse and modify
    // the phone number... first we strip anything that's not a number from the textfield, and then
    // depending on the current value we append formatting characters to make it pretty
    let currentValue: NSString = self.phoneNumberTextField.text
    let strippedValue: NSString = currentValue.stringByReplacingOccurrencesOfString("[^0-9]", withString: "", options: .RegularExpressionSearch, range: NSMakeRange(0, currentValue.length))
    var formattedString: NSString = ""
    if strippedValue.length == 0 {
        formattedString = "";
    }
    else if strippedValue.length < 3 {
        formattedString = "(" + (strippedValue as String)
    }
    else if strippedValue.length == 3 {
        formattedString = "(" + (strippedValue as String) + ") "
    }
    else if strippedValue.length < 6 {
        formattedString = "(" + strippedValue.substringToIndex(3) + ") " + strippedValue.substringFromIndex(3)
    }
    else if strippedValue.length == 6 {
        formattedString = "(" + strippedValue.substringToIndex(3) + ") " + strippedValue.substringFromIndex(3) + "-"
    }
    else if strippedValue.length <= 10 {
        formattedString = "(" + strippedValue.substringToIndex(3) + ") " + strippedValue.substringWithRange(NSMakeRange(3, 3)) + "-" + strippedValue.substringFromIndex(6)
    }
    else if strippedValue.length >= 11 {
        formattedString = "(" + strippedValue.substringToIndex(3) + ") " + strippedValue.substringWithRange(NSMakeRange(3, 3)) + "-" + strippedValue.substringWithRange(NSMakeRange(6, 4))
    }
    self.phoneNumberTextField.text = formattedString as String
}

我使用此代码,如上所示,它的工作原理。当用户键入任何字符时,formatPhoneNumber函数适用于每个字符。

    self.phoneNumberTextField.addTarget(self, action: "formatPhoneNumber", forControlEvents: .EditingChanged)

您必须在viewDidLoad中添加此行。 希望它能为你效用