如何实施模态日期选择器?
我想要发生的是当用户输入文本字段时,会创建一个包含日期选择器的新视图。从那里,用户可以交互并选择日期。当视图关闭时,它应该以某种方式将日期返回给它的调用者。这可能吗?
顺便说一句,由于篇幅原因,我无法将日期选择器放在我的主表单上。提前致谢。
答案 0 :(得分:12)
使用代表!
部首:
@class DatePickerController;
@protocol DatePickerControllerDelegate
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date;
@end
@interface DatePickerController : UIViewController {
UIDatePicker *datePicker;
NSObject <DatePickerControllerDelegate> *delegate;
}
@property (nonatomic, retain) UIDatePicker *datePicker;
@property (nonatomic, assign) NSObject <DatePickerControllerDelegate> *delegate;
@end
类:
@implementation DatePickerController
- (void) loadView {
self.view = [[[UIView alloc] init] autorelease];
self.datePicker = [[[UIDatePicker alloc] init] autorelease];
[self.view addSubview:self.datePicker];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Done" forState:UIControlStateNormal];
button.center = CGPointMake(160,240);
[button addTarget:self action:@selector(done) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
}
- (void) done {
[delegate datePickerController:self didPickDate:datePicker.date];
}
- (void) dealloc {
[datePicker release];
[super dealloc];
}
@end
如果您愿意,可以使用NIB替换loadView中的所有垃圾。只需确保将datePicker声明为IBOutlet。 当你想要真正使用它时:
- (void) pickDate {
DatePickerController *screen = [[[DatePickerController alloc] init] autorelease];
screen.delegate = self;
[self presentModalViewController:screen animated:YES];
}
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date {
[self doSomethingWithDate:date];
[controller dismissModalViewControllerAnimated:YES];
}
答案 1 :(得分:2)
更简单的工作解决方案:
在你的.h:
@property (nonatomic,strong) IBOutlet UIDatePicker *datePicker;
@property (weak, nonatomic) IBOutlet UITextField *historyDateSelect;
@property (nonatomic, retain) UIToolbar *dateToolbar;
在你的.m:
- (void)viewDidLoad
{
[super viewDidLoad];
self.datePicker = [[UIDatePicker alloc]init];
[self.datePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObject:doneButton]];
self.dateToolbar = toolbar;
self.historyDateSelect.inputView = self.datePicker;
self.historyDateSelect.inputAccessoryView = self.dateToolbar;
}
就是这样。 (我在当地测试并且有效)