Last active
November 1, 2015 15:57
-
-
Save mukhortov/810a9c80cd895fee6cb3 to your computer and use it in GitHub Desktop.
MAC address text field formatter for UITextField
This file contains hidden or 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
| // | |
| // TextFieldMacAddress.swift | |
| // | |
| // Created by Peter Mukhortov on 01/11/2015. | |
| // Copyright © 2015 Peter Mukhortov. All rights reserved. | |
| // | |
| // MAC address text field formatter for UITextField | |
| // | |
| import Foundation | |
| import UIKit | |
| class TextFieldMacAddress: UITextField { | |
| override func awakeFromNib() { | |
| super.awakeFromNib() | |
| self.addTarget(self, action: "textFieldResetStyles", forControlEvents: UIControlEvents.EditingDidBegin) | |
| self.addTarget(self, action: "didEndEditing", forControlEvents: UIControlEvents.EditingDidEnd) | |
| self.addTarget(self, action: "formatMacAddress", forControlEvents: UIControlEvents.EditingChanged) | |
| } | |
| func textFieldIsValid() { | |
| self.textColor = UIColor.greenColor() | |
| } | |
| func textFieldIsInvalid() { | |
| self.textColor = UIColor.redColor() | |
| } | |
| func textFieldResetStyles() { | |
| self.textColor = UIColor.blackColor() | |
| } | |
| func didEndEditing() { | |
| if isValid() { | |
| textFieldIsValid() | |
| } else { | |
| textFieldIsInvalid() | |
| } | |
| } | |
| func isValid() -> Bool { | |
| let macRegex = "([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})" | |
| if let macTest = NSPredicate(format: "SELF MATCHES %@", macRegex) as NSPredicate! { | |
| return macTest.evaluateWithObject(self.text) | |
| } | |
| return false | |
| } | |
| func formatMacAddress() { | |
| let stringMaxLength = 12 | |
| var string = self.text!.stringByReplacingOccurrencesOfString("[^0-9A-Fa-f]", withString: "", options: .RegularExpressionSearch) | |
| var formattedString = String() | |
| if string.characters.count > stringMaxLength { | |
| string = string.substringToIndex(string.startIndex.advancedBy(stringMaxLength)) | |
| } | |
| for char in string.characters { | |
| if (formattedString.characters.count + 1) % 3 == 0 { | |
| formattedString.appendContentsOf(":") | |
| } | |
| formattedString.append(char) | |
| } | |
| self.text = formattedString | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment