How to Display Time Picker On Textfield Click in Xcode
Open Xcode and create a new Single View Application. For product name, use TextFieldTimePicker and then fill out the Organization Name and...
For setting up the user interface, first, I embed the view controller inside a navigation controller. Go to Interface Builder, and then click the View Controller. Once the View Controller has been clicked, select the "Editor" -> "Embed in" -> "Navigation Controller".
Next, let's add a bar button item, a label, and a text field. I configured the bar button item to have a title of "Done". I also changed the label text to "00:00" and textfield's placeholder to "Input Time Here".
We will need to connect the user interface's to the view controller. Select the assistant editor and open the ViewController.m file. Ctrl and drag from the "Done" button to the class section and create the following action.
Repeat the same process for label and textfield, except that they should be an outlet and not an action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | -( void )setUpTextFieldDatePicker { UIDatePicker *datePicker = [[UIDatePicker alloc]init]; datePicker.datePickerMode = UIDatePickerModeTime; [datePicker setDate:[NSDate date]]; [datePicker addTarget:self action: @selector (updateTextField:) forControlEvents:UIControlEventValueChanged]; [self.txtField_timeTextField setInputView:datePicker]; } -( void )updateTextField:(id)sender { UIDatePicker *picker = (UIDatePicker*)self.self.txtField_timeTextField.inputView; NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; [outputFormatter setDateFormat:@ "HH:mm" ]; //24hr time format NSString *dateString = [outputFormatter stringFromDate:picker.date]; self.self.txtField_timeTextField.text = [NSString stringWithFormat:@ "%@" ,dateString]; } |
1 | [self setUpTextFieldDatePicker]; |
Inside the btn_showTime, add the following lines of code to update the label and hide the date picker once the button is cliced.
1 2 | self.lbl_timeLabel.text = self.txtField_inputTextfield.text; [self.txtField_inputTextfield resignFirstResponder]; |
You can download the source code of the TimeTextField at my repository on bitbucket.
Post a Comment