如何实现模态日期选择器?

时间:2010-09-29 10:24:35

标签: iphone objective-c uidatepicker

我正在使用Ed Marty对问题here的回答的代码,但我遇到了一些问题。

点击按钮后,我出现了日期选择器,但是“完成”按钮不是。我也从行中得到错误:

[delegate datePickerController:controller didPickDate:datePicker.date];

错误讯息:

  

'控制器'未声明(首次使用此功能)

总而言之,我有6个文件:

  • ModalDatePickerViewController.m
  • ModalDatePickerViewController.h
  • ModalDatePickerAppDelegate.m
  • ModalDatePickerAppDelegate.h
  • DatePickerController.m
  • DatePickerController.h

我的DatePickerController.h看起来像:

    #import <UIKit/UIKit.h>


@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

和DatePickerController.m:

#import "DatePickerController.h"

@implementation DatePickerController

@synthesize datePicker;
@synthesize delegate;

- (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,230);
    [button addTarget:self action:@selector(done) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button];
}

- (void) done {
    [delegate datePickerController:controller didPickDate:datePicker.date];
}

- (void) dealloc {
    [datePicker release];
    [super dealloc];
}

@end

在主视图中,我有一个按钮,可以调用此类,如下所示:

#import "ModalDatePickerViewController.h"

@implementation ModalDatePickerViewController

- (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];
}
- (IBAction)HitMe:(id)sender {
    [self pickDate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)dealloc {
    [super dealloc];
}
@end

#import <UIKit/UIKit.h>
#import "DatePickerController.h"

@interface ModalDatePickerViewController : UIViewController <DatePickerControllerDelegate> {

}

- (IBAction)HitMe:(id)sender;

@end

1 个答案:

答案 0 :(得分:4)

在这一行:

[delegate datePickerController:controller didPickDate:datePicker.date];

尝试将controller替换为self