我的UIViewController
里面有UIDatePicker
。我在标题类中将UIDatePicker
与IBOutlet
属性相关联,因为我在我的应用中使用了故事板:
#import <UIKit/UIKit.h>
@protocol CreationDateDelegate <NSObject>
@optional
-(void)selectedDateIs:(NSString*)dateValue;
@end
@interface SelectCreationDateViewController : UIViewController
{
IBOutlet UIDatePicker *datePicker;
}
@property (nonatomic,assign)id<CreationDateDelegate>creationDateDelegate;
@property (nonatomic,retain) IBOutlet UIDatePicker *datePicker;
@end
--- .m -----
#import "SelectCreationDateViewController.h"
@interface SelectCreationDateViewController ()
{
NSString *dateFromString;
}
@end
@implementation SelectCreationDateViewController
@synthesize creationDateDelegate,datePicker;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
}
return self;
}
- (void)viewDidLoad
{
self.title = @"Select creation date";
[super viewDidLoad];
[datePicker setHidden:NO];
datePicker.timeZone = [NSTimeZone localTimeZone];
[datePicker setDatePickerMode:UIDatePickerModeDate];
[datePicker addTarget:self action:@selector(changeValueOfDatePicker:) forControlEvents:UIControlEventValueChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *dateFromString = [formatter stringFromDate:datePicker.date];
[self.creationDateDelegate selectedDateIs:dateFromString];
}
-(void)changeValueOfDatePicker:(id)sender{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
dateFromString = [formatter stringFromDate:datePicker.date];
[self.creationDateDelegate selectedDateIs:dateFromString];
NSLog(@"Date from string value equal %@",dateFromString);
}
@end
为什么每次更改DatePicker返回值的值都不会改变?有任何想法吗?另外,如果我在代码中犯了任何错误,请告诉我。
答案 0 :(得分:0)
通过添加此行代码修复,
仅在您使用iOS7时 - 在method(void)viewDidLoad方法
中[self.datePicker setDate:[NSDate date] animated:YES];
答案 1 :(得分:0)
也设置一些日期格式
-(void)changeValueOfDatePicker:(id)sender{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
dateFromString = [formatter stringFromDate:datePicker.date];
[self.creationDateDelegate selectedDateIs:dateFromString];
NSLog(@"Date from string value equal %@",dateFromString);
}