Search code examples
iosobjective-ctimepicker

Time not updating in label after selection in TimePicker


I am new to IOS i need to display time picker with current time in label and changed in time picker that value also updated in same label. After that i want to close that time Picker also after selection.

Coding for time picker:

- (IBAction)pickuptime1:(id)sender {

    self.datePicker = [[UIDatePicker alloc] init];
    self.datePicker.frame = CGRectMake(0, 250,325,300); // set frame as your need
    self.datePicker.datePickerMode = UIDatePickerModeTime;
    [self.view addSubview: self.datePicker];
    //UILabel  * label = [[UILabel alloc] initWithFrame:CGRectMake(40, 70, 300, 50)];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date];
    label2.text = currentTime;
    [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:datePicker];
    [self.view addSubview:label2];

   }

Method coding:

- (void)dateChanged:(id)sender
{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date];
    NSLog(@"%@", currentTime);


}

Solution

  • accepted Implement the delegate method, pickerView:didSelectRow:inComponent:. This is called by the picker view when you select an item. Get the value from your array based on the row and component, and populate your label.

     - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
         self.label.text = _myArray[row];
     } 
    

    Or check this one also

    • You can't change the appearance of UIDatePicker.
    • You can store it in a property and when you need to remove it from superview call [datePicker removeFromSuperview];
    • You need a date formatter to get a string value from date. Some like this:

      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterShortStyle];

    • And for setting the label with date:

      self.dateLabel.text = [dateFormatter stringFromDate:datePicker.date];