Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

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 Company Identifier with your customary values. Select iPhone for Devices.

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.

Inside the ViewController.m, add the following lines of code to set-up the date picker and make it the input view of the text field:

    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];

    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];

Then, we'll have to set up the date picker once the view controller is loaded. Call the setUpTextFIeldDatPicker inside the viewDidLoad
[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.
self.lbl_timeLabel.text = self.txtField_inputTextfield.text;
[self.txtField_inputTextfield resignFirstResponder];
Build and Run, a date picker should now appear when the text field is clicked.

You can download the source code of the TimeTextField at my repository on bitbucket.

Display Time Picker On Textfield Click in Xcode Display Time Picker On Textfield Click in Xcode Reviewed by Edmond Legaspi on Friday, August 01, 2014 Rating: 5

No comments:

Powered by Blogger.