Last active
August 29, 2015 14:17
-
-
Save phamquochoan/e9d1b76fc7a87bcf1984 to your computer and use it in GitHub Desktop.
Folk from: https://gist.github.com/sdrew/5230424 with some tuning.
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
lazy var timeFormatter: NSNumberFormatter! = { | |
var formatter = NSNumberFormatter() | |
formatter.numberStyle = .NoStyle | |
formatter.groupingSize = 2 | |
formatter.groupingSeparator = ":" | |
formatter.usesGroupingSeparator = true | |
formatter.maximumFractionDigits = 0 | |
formatter.minimumIntegerDigits = 4 | |
formatter.maximumIntegerDigits = 4 | |
return formatter | |
}() | |
extension YourController: UITextFieldDelegate { | |
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { | |
var input = textField.text.stringByReplacingOccurrencesOfString(":", withString: "") | |
if countElements(string) == 0 { | |
input = input.substringToIndex(advance(input.startIndex, countElements(input) - 1)) | |
} | |
else { | |
input = input.stringByAppendingString(string) | |
} | |
let value = NSNumber(double: (input as NSString).doubleValue) | |
textField.text = timeFormatter.stringFromNumber(value) | |
return false | |
} | |
func textFieldDidBeginEditing(textField: UITextField) { | |
if countElements(textField.text) == 0 { | |
textField.text = "00:00" | |
} | |
} | |
private func validateTime(time: String) -> Bool { | |
if countElements(time) == 0 { return false } | |
let array = time.componentsSeparatedByString(":") as [NSString] | |
if let hour = array.first?.integerValue { | |
if hour > 23 { return false } | |
} | |
if let minute = array.last?.integerValue { | |
if minute > 59 { return false } | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment