如何在iOS7中将UIDatePicker添加到UIALertView

我在我的一个视图中实现了datepicker,方法是将datepicker添加到Alertview。 现在在iOS 7中,我无法在alertview上finddatepicker,当我search到时,我们不能在iOS7中添加任何东西给alertview。

我的要求是当我selectDOB文本框时,我必须显示Datepickerview并修改date,并将更改后的值存储到文本框中。

现在我的问题是如何显示在alertview datepicker。

我试图在视图上显示,但是当试图从视图中删除datpicker它不起作用。

我知道这是一个较老的问题,但我相信以下内容允许OP请求的内容,我不认为会违反Apple AlertView层次结构更改的规则:

- (void)requestDateOfBirth { UIDatePicker *birthDatePicker; UIAlertView *setBirthDate; NSDateFormatter *birthDateFormatter; UITextField *birthDateInput; //create the alertview setBirthDate = [[UIAlertView alloc] initWithTitle:@"Date of Birth:" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; setBirthDate.alertViewStyle = UIAlertViewStylePlainTextInput; //create the datepicker birthDatePicker = [[UIDatePicker alloc] init]; [birthDatePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged]; birthDatePicker.datePickerMode = UIDatePickerModeDate; birthDatePicker.date = [NSDate date]; //get the textfield provided in the plain text alertview birthDateInput = [setBirthDate textFieldAtIndex:0]; //change the textfields inputView to the date picker birthDateInput.inputView = birthDatePicker; [birthDateInput setTextAlignment:NSTextAlignmentCenter]; //create a date formatter to suitably show the date birthDateFormatter = [[NSDateFormatter alloc] init]; [birthDateFormatter setDateStyle:NSDateFormatterShortStyle]; //set the current date into the textfield birthDateInput.text = [birthDateFormatter stringFromDate:[NSDate date]]; //show the alert view and activate the textfield [setBirthDate show]; [birthDateInput becomeFirstResponder]; } 

那么不要忘记处理dateselect器中的更改

 - (void) dateChanged:(id)sender { NSDateFormatter *birthDateFormatter; UIDatePicker *birthDatePicker = (UIDatePicker *)sender; birthDateFormatter = [[NSDateFormatter alloc] init]; [birthDateFormatter setDateStyle:NSDateFormatterShortStyle]; birthDateInput.text = [birthDateFormatter stringFromDate:birthDatePicker.date]; } 

我希望这有帮助

在iOS 7中,您可以使用

 [alertView setValue:yourDataPicker forKey:@"accessoryView"]; 

完整的解释是在这里

UIAlertView的层次结构是私有的,不应该被修改。

从苹果文档

UIAlertView类旨在按原样使用,不支持子类。 这个类的视图层次是私有的,不能被修改。

在iOS 6之前,你可以添加一些视图到UIAlertView子视图的层次结构,但是这似乎不再适用于iOS 7了。自从beta4发布以来,iOS7宣布的contentView属性就成为了一个私有的ivar,因此无法添加子视图来提醒视图。

 UIView *_contentViewNeue; 

欲了解更多关于这个请参阅这个苹果开发论坛讨论 (您将需要login)

在这种情况下,您应该创build一个模仿UIAlertView的自定义视图,然后使用它来添加select器视图。

希望有所帮助!