3

我是 ios 的初学者,请帮助我如何在用户按下按钮时显示弹出日历。我已经在下面有我的按钮

UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame= CGRectMake(60, 560, 150, 30);
[button setTitle:@"Select Date" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
4

1 回答 1

15

在 .h 文件中

 UIDatePicker *datepicker;
 UIPopoverController *popOverForDatePicker;

请在 .h 文件中设置委托 UIPopoverControllerDelegate

在 .m 文件中

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame= CGRectMake(60, 560, 150, 30);
    [button setTitle:@"Select Date" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor redColor]];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}
- (void)buttonAction:(UIButton *)sender
{
    UIViewController *viewController = [[UIViewController alloc]init];
    UIView *viewForDatePicker = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];

    datepicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
    datepicker.datePickerMode = UIDatePickerModeDate;
    datepicker.hidden = NO;
    datepicker.date = [NSDate date];
    [datepicker addTarget:self action:@selector(LabelChange:) forControlEvents:UIControlEventValueChanged];

    [viewForDatePicker addSubview:datepicker];
    [viewController.view addSubview:viewForDatePicker];

    popOverForDatePicker = [[UIPopoverController alloc]initWithContentViewController:viewController];
    popOverForDatePicker.delegate = self;
    [popOverForDatePicker setPopoverContentSize:CGSizeMake(200, 100) animated:NO];
    [popOverForDatePicker presentPopoverFromRect:sender.frame inView:self.view  permittedArrowDirections:(UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown| UIPopoverArrowDirectionLeft|UIPopoverArrowDirectionRight) animated:YES];
}
-(void)LabelChange:(id)sender
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    df.dateStyle = NSDateFormatterMediumStyle;
    NSLog(@"%@",[NSString stringWithFormat:@"%@",[df stringFromDate:datepicker.date]]);
}
于 2013-04-04T06:26:49.843 回答