我是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];
答案 0 :(得分: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]]);
}