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 に答える