如何将 Textfiled.text 格式化为土耳其语 Phone 格式?

How to Format Textfiled.text in Turkish Phone Format?

我有一个 textfield,它只需要 phone 号码,我正在尝试将其格式化为土耳其格式号码,看起来像这样 (555) 555 5555。我该怎么做在 Swift?

好吧,如果我们假设所有土耳其数字都是 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.

执行验证

你可以在 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
            }
        }
    }
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 中添加这一行。 希望它对你有用