在TimePicker中选择后,时间不在标签中更新

时间:2016-05-14 06:09:36

标签: ios objective-c timepicker

我是IOS新手我需要在标签中显示当前时间的时间选择器,并在时间选择器中更改该值也在同一标签中更新。之后我想在选择之后关闭那个时间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];

   }

方法编码:

- (void)dateChanged:(id)sender
{

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


}

2 个答案:

答案 0 :(得分:0)

接受 实现委托方法,pickerView:didSelectRow:inComponent:。选择项目时,选择器视图会调用此选项。根据行和组件从数组中获取值,并填充标签。

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

或者也检查一下

  • 您无法更改UIDatePicker的外观。
  • 您可以将其存储在属性中,以及何时需要将其删除 superview调用[datePicker removeFromSuperview];
  • 您需要一个日期格式化程序才能从日期获取字符串值。有些人喜欢 这样:

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

  • 并使用日期设置标签:

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

答案 1 :(得分:0)

它非常简单,你只需要实现一个方法就可以更新日期和时间。时间隐含地看一下代码..

-(IBAction)done_action:(id)sender{
    self.viewDatePicker.hidden=YES;
    [self.datePicker setDatePickerMode:UIDatePickerModeDate];
    [self.datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    _yourCustomLabel.text = [dateFormatter stringFromDate:self.datePicker.date];
}

// method invokes while scrolling on date picker
-(IBAction)onDatePickerValueChanged:(UIDatePicker *)datePicker{
    // yourLabel to show current time while scroll on datePicker
    self.yourLabel.text = [dateFormatter stringFromDate:datePicker.date];
}

将您的datePicker放在最初隐藏或相应自定义的视图中。