UIPickerView中的行选择

时间:2018-05-17 06:36:09

标签: ios objective-c uidatepicker

我想在标签上显示选择UIDatePickerView行的当前日期,我的问题是当我打开我的日期选择器时,它在选择行时没有显示标签上的任何内容但是当我移动日期时选择器视图,它开始更新我的标签,我无法修复它。我想在触摸日期选择器视图行时显示日期。我甚至还添加了TouchUpInside行方法,但是,它还没有工作

这是我的代码段:

- (IBAction)btn_calendar_event:(id)sender {
    // ADD UIDatePicker and open it
    if (self.picker) {
        [self.toolbar removeFromSuperview];
        [self.picker removeFromSuperview];
    }
    [self hideKeyboard];
    self.picker = [[UIDatePicker alloc] init];
    self.picker.backgroundColor = [UIColor whiteColor];
    [self.picker setValue:[UIColor blackColor] forKey:@"textColor"];

    self.picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.picker.datePickerMode = UIDatePickerModeDate;
  forControlEvents:UIControlEventValueChanged];

[self.picker addTarget:self action:@selector(dueDateChanged :) forControlEvents:UIControlEventTouchUpInside];         [self.picker addTarget:self action:@selector(dueDateChanged :) forControlEvents:UIControlEventValueChanged];      }

// dueDateChanged method 

-(void) dueDateChanged:(UIDatePicker *)sender {
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];

    NSLog(@"Picked the date %@", [dateFormatter stringFromDate:[sender date]]);
   _txtf_birthDate.text = [dateFormatter stringFromDate:[sender date]];

}

// Done button Action 

-(void)onDoneButtonClick {
    [self dueDateChanged :  self.picker];
    [self.toolbar removeFromSuperview];
    [self.picker removeFromSuperview];
}

1 个答案:

答案 0 :(得分:1)

问题在于,当您初次启动您的选择器时,您的选择器不会设置标签的日期,因此它只会在触发dueDateChanged时更新,因此当您初始化日期选择器时选择您想要的日期显示为默认日期并以标签显示,如

[self.picker addTarget:self action:@selector(dueDateChanged:) forControlEvents:UIControlEventValueChanged]之后只需在您的选择器中添加默认日期,如: -

self.picker.date=[NSDate date]; // add the default initial date
[self dueDateChanged:self.picker];

根据您的要求"如果我想在选择行上显示当前日期然后如何操作,现在设置默认初始日期甚至没有选择日期选择器视图行 "你可以从你想要显示日期的地方添加任意一行

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
_txtf_birthDate.text = [dateFormatter stringFromDate:[NSDate date]];