简体   繁体   English

如何在UITextField iOS Swift中添加连字符?

[英]How to add Hyphens in UITextField iOS Swift?

Need the following format of Numbers with Hyphen when typing in UITextField. 在UITextField中键入时,需要以下带连字符的数字格式。

在此处输入图片说明

// Restrict entry to format 123-456-7890

You can try with similar code. 您可以尝试使用类似的代码。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // All digits entered
    if range.location == 12 {
        return false
    }
    // Reject appending non-digit characters
    if range.length == 0 && !NSCharacterSet.decimalDigitCharacterSet().characterIsMember(string.characterAtIndex(0)) {
        return false
    }
    // Auto-add hyphen before appending 4rd or 7th digit
    if range.length == 0 && (range.location == 3 || range.location == 7) {
        textField.text = "\(textField.text!)-\(string)"
        return false
    }
    // Delete hyphen when deleting its trailing digit 
    if range.length == 1 && (range.location == 4 || range.location == 8) {
        range.location--
        range.length = 2
        textField.text = textField.text!.stringByReplacingCharactersInRange(range, withString: "")
        return false
    }
    return true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM