我试图在点击按钮时显示日期选择器。我希望日期选择器位于iPhone的可见视图的中心。我的基本视图是UIScrollView.Its工作正常,直到我滚动我的视图。只要我向上滚动视图并单击日期选择器按钮,它就会向上移动。 我正在使用的代码是
- (void)changeDate:(UIDatePicker *)sender {
NSLog(@"New Date: %@", sender.date);
}
- (void)removeViews:(id)object {
scrollview.scrollEnabled = YES;
[[self.view viewWithTag:9] removeFromSuperview];
[[self.view viewWithTag:10] removeFromSuperview];
[[self.view viewWithTag:11] removeFromSuperview];
}
- (void)dismissDatePicker:(id)sender {
scrollview.scrollEnabled = YES;
CGRect toolbarTargetFrame = CGRectMake(0, self.view.bounds.size.height, 320, 44);
CGRect datePickerTargetFrame = CGRectMake(0, self.view.bounds.size.height+44, 320, 216);
[UIView beginAnimations:@"MoveOut" context:nil];
[self.view viewWithTag:9].alpha = 0;
[self.view viewWithTag:10].frame = datePickerTargetFrame;
[self.view viewWithTag:11].frame = toolbarTargetFrame;
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(removeViews:)];
[UIView commitAnimations];
}
- (IBAction)callDP:(id)sender {
if ([self.view viewWithTag:9]) {
return;
}
scrollview.scrollEnabled = NO;
CGRect toolbarTargetFrame = CGRectMake(0, self.view.bounds.size.height/2-216/2-44, 320, 44);
CGRect datePickerTargetFrame = CGRectMake(0, self.view.bounds.size.height/2-216/2, 320, 216);
UIView *darkView = [[UIView alloc] initWithFrame:self.view.bounds];
darkView.alpha = 0;
darkView.backgroundColor = [UIColor blackColor];
darkView.tag = 9;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissDatePicker:)] ;
[darkView addGestureRecognizer:tapGesture];
[self.view addSubview:darkView];
UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height+44, 320, 216)];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.tag = 10;
[datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, 320, 44)];
toolBar.tag = 11;
toolBar.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissDatePicker:)];
[toolBar setItems:[NSArray arrayWithObjects:spacer, doneButton, nil]];
[self.view addSubview:toolBar];
[UIView beginAnimations:@"MoveIn" context:nil];
toolBar.frame = toolbarTargetFrame;
datePicker.frame = datePickerTargetFrame;
darkView.alpha = 0.5;
[UIView commitAnimations];
}