我使用了另一种方法来消除 UIDatePicker。
创建一个 XIB (nib) 文件并向其中添加一个 UIDatePicker,然后调整视图大小,使其仅适合 UIDatePicker,在您的 ViewController(或您使用的任何类,当然是合成)中创建一个属性(使其强大且非原子)。
@property (nonatomic, strong) UIView *myDatePickerView;
@synthesize myDatePickerView;
然后创建一个loadDatePickerView 方法
- (void) loadDatePickerView
{
UINib *nib = [UINib nibWithNibName:kNIBname bundle:[NSBundle mainBundle]];
NSArray *views = [nib instantiateWithOwner:self options:nil];
self.myDatePickerView = [views firstObject];
[myDatePickerView setFrame:CGRectMake(0, 318, 320, 162)];
[self.view addSubview:myDatePickerView];
}
实现 UITextFieldDelegate,并在textFieldDidBeginEditing 方法中调用 loadDatePickerView 方法,
[self loadDatePickerView];
使函数创建一个属性,它是一个UIDatePicker 实例
@property (nonatomic,strong)
UIDatePicker *myDatePicker;
(当然是合成)
现在像这样创建一个IBAction:
-(IBAction)datePickerValueChanged:(UIDatePicker *)sender
{
myDatePicker = [[myDatePickerView subviews] lastObject];
//now you can do whatever you want with the DatePicker
}
现在将 IBAction 连接到 XIB 文件中的选择器,这样 XIB 现在是您在 VC 中创建的 UIDatePicker 实例,如果您希望它消失,您可以添加一个UITapGestureRecognizer(在 ViewDidLoad 中),选择器将是另一个 IBAction它将 myDatePickerView 从它的 superView 中删除,如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dropPicker:)];
[self.view addGestureRecognizer:tap];
[self datePickerValueChanged:myDatePicker];
}
-(IBAction)dropPicker:(id)sender
{
[myDatePickerView removeFromSuperview];
}