我有一个我制作的iPhone应用程序,在一个视图中有一个UIDatePicker。
当你最初启动应用程序时,视图第一次加载;在viewDidLoad中,我将UIDatePicker设置为当前日期/时间。它运行良好。
现在,如果用户最小化应用程序并做其他事情(但没有杀死应用程序),然后返回应用程序,则当您返回该视图时,日期/时间不会更新。
我想知道在加载视图时(例如,当你在视图已经打开但位于后台后返回到它时),我将如何"刷新"UIDatePicker。
有什么想法吗?
如果没有快速/简单的方法——我还考虑过在UIDatePicker最初加载时创建一个与时间相关的变量——那么当它被重新加载时,让它检查一下自上次查看以来是否超过了10分钟。如果是,那么它会将UIDatePicker设置为当前日期/时间。
有什么想法吗?
您的视图加载后可能看起来像这个
- (void)viewDidLoad {
[super viewDidLoad];
// listen for notifications for when the app becomes active and refresh the date picker
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDatePicker) name:UIApplicationDidBecomeActiveNotification object:nil];
}
然后在您的视图中将出现:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// refresh the date picker when the view is about to appear, either for the
// first time or if we are switching to this view from another
[self refreshDatePicker];
}
并将刷新方法简单地实现为:
- (void)refreshDatePicker {
// set the current date on the picker
[self.datepicker setDate:[NSDate date]];
}
在和这两种情况下,当视图在应用程序打开时从另一个视图切换到此视图时,以及当应用程序处于后台并在该视图已打开的情况下进入前台时,这将更新您的日期选择器。
您应该能够在viewWillAppear方法中设置日期。每当视图出现在屏幕上时,都会调用该方法。
- (void) viewWillAppear: (BOOL) animated
{
[super viewWillAppear:animated];
// update the date in the datepicker
[self.datepicker setDate:[NSDate date]];
}