IOS之UI状态保持与恢复

为了实现点击Home键使程序退出,可以在设置属性*-info.plist修改Application does not run in background属性值为YES

为实现UI的状态保持和恢复,包括APP层面和storyboard层面,首要条件就是需要在AppDelegate.m文件添加以下两个方法。

- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder {
    return YES;
}

- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder {
    return YES;
}

 1.APP层面

          在APPDelegate.m中添加如下代码:

//本例子为记录上一次退出的时间,在下一次打开时显示出来
- (void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder {
    // 获取系统当前时间
    NSDate *date = [NSDate date];
    NSTimeInterval sec = [date timeIntervalSinceNow];
    NSDate *currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
    
    //设置时间输出格式:
    NSDateFormatter *df = [[NSDateFormatter alloc] init ];
    [df setDateFormat:@"yyyy年MM月dd日 HH小时mm分ss秒"];
    NSString *na = [df stringFromDate:currentDate];
    
    
    [coder encodeObject:na forKey:@"lastShutdownTime"];
    
    NSLog(@"application willEncodeRestorableStateWithCoder 时间为:%@", na);
    
    }

- (void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder {
    NSString * currentTime = [coder decodeObjectForKey:@"lastShutdownTime"];
    AppUtils *appUtils = [AppUtils alloc];
    if (currentTime) {
        [appUtils showDialog:@"上次关闭时间" message:currentTime];
    }
}


//附带AppUtils类文件
//AppUtils.h
#import <Foundation/Foundation.h>

@interface AppUtils : NSObject

- (void)showDialog:(NSString *)title message:(NSString *)message;

@end

//AppUtils.m
#import "AppUtils.h"

@implementation AppUtils

- (void)showDialog:(NSString *)title message:(NSString *)message{
    UIAlertView *alert = [[UIAlertView  alloc]
                                        initWithTitle:title
                                        message:message
                                        delegate:nil
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
    [alert show];
}

@end

 2.storyboard层面

(1)选择指定的storyboard的ViewController,将其restorationID设置为viewController



 

(2)添加下面的方法,实现退出时保存文本框的文本信息。

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
    NSLog(@"encodeRestorableStateWithCoder");
    [super encodeRestorableStateWithCoder:coder];
    [coder encodeObject:self.editText.text forKey:@"kSaveKey"];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    NSLog(@"decodeRestorableStateWithCoder");
    [super decodeRestorableStateWithCoder:coder];
    self.editText.text = [coder decodeObjectForKey:@"kSaveKey"];
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值