ios 当用户按下按钮时弹出日期选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15801795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:01:15 来源:igfitidea点击:
Popup datepicker when user presses a button
提问by Godric
im a beginner in ios, pls help me how to show a popup calendar when user press a button. I already have my button below
我是 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];
回答by Manohar Perepa
In .h file
在 .h 文件中
UIDatePicker *datepicker;
UIPopoverController *popOverForDatePicker;
Please set the Delegate in .h fileUIPopoverControllerDelegate
请在 .h 文件中设置委托UIPopoverControllerDelegate
In .m File
在 .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]]);
}