-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimePickerTextField.swift
54 lines (46 loc) · 1.66 KB
/
TimePickerTextField.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import UIKit
class TimePickerTextField: UITextField, UIPickerViewDelegate, UITextFieldDelegate {
private var picker = UIDatePicker()
private var toolBar = UIToolbar()
var time: String? {
didSet {
text = time
let formatter = NSDateFormatter()
formatter.dateFormat = kDateFormat
if let time = time {
if let date = formatter.dateFromString(time) {
picker.date = date
}
}
}
}
var doneText: String = "OK" {
didSet {
doneButton.title = doneText
}
}
var completion:(()->Void)?
private let kDateFormat = "HH:mm"
private var doneButton: UIBarButtonItem!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupPickerView()
tintColor = UIColor.clearColor()
}
private func setupPickerView() {
doneButton = UIBarButtonItem(title: doneText, style: UIBarButtonItemStyle.Plain, target: self, action: "doneButtonDidPush:")
let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolBar.sizeToFit()
toolBar.setItems([spacer, doneButton], animated:false)
picker.datePickerMode = UIDatePickerMode.Time
inputView = picker
inputAccessoryView = toolBar
}
func doneButtonDidPush(sender: AnyObject) {
resignFirstResponder()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = kDateFormat
time = dateFormatter.stringFromDate(picker.date)
completion?()
}
}