Last active
December 17, 2018 21:24
-
-
Save wbbernardes/1b22c09cafa26820dfcc905cdd1d2e12 to your computer and use it in GitHub Desktop.
Exemplo de máscara para CPF e CEP sem uso de dependência externa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// ProjetoPodTest | |
// | |
// Created by Wesley Brito on 24/11/18. | |
// Copyright © 2018 Wesley Brito. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var textField: UITextField! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
} | |
} | |
extension ViewController: UITextFieldDelegate { | |
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
var appendString = "" | |
if textField.placeholder == "CPF" { | |
if range.length == 0 { | |
switch range.location { | |
case 3: | |
appendString = "." | |
case 7: | |
appendString = "." | |
case 11: | |
appendString = "-" | |
default: | |
break | |
} | |
} | |
textField.text?.append(appendString) | |
if (textField.text?.count)! > 13 && range.length == 0 { | |
return false | |
} | |
} else if textField.placeholder == "CEP" { | |
if range.length == 0 { | |
switch range.location { | |
case 2: | |
appendString = "." | |
case 6: | |
appendString = "-" | |
default: | |
break | |
} | |
} | |
textField.text?.append(appendString) | |
if (textField.text?.count)! > 9 && range.length == 0 { | |
return false | |
} | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment