如何在iOS7中将UIDatePicker添加到UIALertView

3
我在一个视图中实现了日期选择器,将其添加到AlertView中。但是,在iOS 7上我无法在AlertView上找到日期选择器,当我搜索时发现,在iOS7中我们无法向AlertView中添加任何内容。
我的要求是,当我选择出生日期文本字段时,我必须显示Datepickerview,并修改日期,更改的值将存储到textfield中。
现在我的问题是如何在AlertView上显示日期选择器。
我尝试在视图上显示,但尝试从视图中移除datpicker时它没有起作用。
3个回答

3

我知道这是一个比较旧的问题,但我认为以下方法可以满足OP的要求,并且不会违反苹果关于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];
}

那么不要忘记处理日期选择器中的更改。
- (void) dateChanged:(id)sender
{
NSDateFormatter *birthDateFormatter;
UIDatePicker *birthDatePicker = (UIDatePicker *)sender;

birthDateFormatter = [[NSDateFormatter alloc] init];
[birthDateFormatter setDateStyle:NSDateFormatterShortStyle];
birthDateInput.text = [birthDateFormatter stringFromDate:birthDatePicker.date];
}

我希望您能从中获益。

谢谢你的帮助 :) - Salman Khakwani

1
在iOS 7中,您可以使用。
[alertView setValue:yourDataPicker forKey:@"accessoryView"];

完整的解释在这里

0

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

来自Apple文档

UIAlertView类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不能修改。

在iOS 6之前,您可以将一些视图添加到UIAlertView的子视图层次结构中,但在iOS 7上似乎不再起作用。自beta4版本以来,宣布为iOS7的contentView属性已成为私有ivar,因此无法向警报视图addSubview

UIView *_contentViewNeue;

如需了解更多信息,请参考Apple开发者论坛讨论(您需要登录)

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

希望能对您有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接