Created
March 19, 2019 17:15
-
-
Save amadeu01/8873b08db596ed59ee66d96c2d41487c to your computer and use it in GitHub Desktop.
PhoneFormatter for eureka.
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
| public class PhoneFormatter: Formatter, FormatterProtocol { | |
| override public func getObjectValue( | |
| _ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, | |
| for string: String, | |
| errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { | |
| guard obj != nil else { return false } | |
| let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "") | |
| obj?.pointee = str as AnyObject | |
| return true | |
| } | |
| public override func string(for obj: Any?) -> String? { | |
| guard let oldString = obj as? String else { | |
| return nil | |
| } | |
| return getNewFormattedString(from: oldString) | |
| } | |
| public func getNewPosition( | |
| forPosition position: UITextPosition, | |
| inTextInput textInput: UITextInput, | |
| oldValue: String?, | |
| newValue: String? | |
| ) -> UITextPosition { | |
| let offset = ((newValue?.count ?? 0) - (oldValue?.count ?? 0)) | |
| return textInput.position(from: position, offset: offset) ?? position | |
| } | |
| private func getNewFormattedString(from oldString: String) -> String { | |
| let oldString = oldString as NSString | |
| let length = oldString.length | |
| let formattedString = NSMutableString() | |
| var index = 0 as Int | |
| if (length - index) > 2 { | |
| let areaCode = oldString.substring(with: NSRange(location: index, length: 2)) | |
| formattedString.appendFormat("(%@) ", areaCode) | |
| index += 2 | |
| } | |
| if length - index > 2 { | |
| let prefix = oldString.substring(with: NSRange(location: index, length: 5)) | |
| formattedString.appendFormat("%@-", prefix) | |
| index += 5 | |
| } | |
| let remainder = oldString.substring(from: index) | |
| formattedString.append(remainder) | |
| return formattedString as String | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment