如何在iOS上禁用一段时间的viewController?

时间:2014-11-17 14:56:05

标签: ios

我希望在用户按下viewController X上的按钮一天后禁用其中一个viewController X(初始视图).viewController Y将在此期间成为初始视图。我该如何正确实现?

1 个答案:

答案 0 :(得分:1)

所以在ViewController X中你想使用nsuserdefaults保存按钮按下时的日期

// Get the current date
    NSDate *now = [NSDate date];
// Save it in nsuserdefaults using the key myDateKet
    [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"myDateKey"];

在你的AppDelegate.m中把这个

     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        // Number of seconds in a day
        double dayInSeconds = 86400; 
        // Get the current date when app opens this gets called
        NSDate *today = [NSDate date];
        // Get the date saved when user pressed the button
        NSDate *savedDate = (NSDate *)[defaults objectForKey:@"myDateKey"];
        // If nil then user has never pressed the button
        if (savedDate == nil) {
             // Therefore view controller x is the root
              self.window.rootViewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"view controller x"];
        } else {
           // Else user has pressed button so compared the dates
           // One day after the saved date
           NSDate *oneDayAfterSaved = [NSDate alloc] initWithTimeInterval:dayInSeconds sinceDate:savedDate];

           // Compare oneDayAfterSaved to today
           NSComparisonResult result = [today compare:oneDayAfterSaved];
           // Check if the date is the same has one day after the saved date or after then
           if (result == NSOrderedSame || result == NSOrderedDescending) {
               // ViewController x is the root
               self.window.rootViewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"view controller x"];
           } else {
               // else if before one day after saved date then view controller y
               self.window.rootViewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"view controller y"];
           }

        }

        return YES;
    }