用户在文本框中输入一些内容,应用程序退出并且终止,当用户再次进来的时候,文本框中还会保持原来输
入的内容。在Interface Builder的Scene中选中View Controller,打开右边的标识检查器 ,设置Restoration ID(恢复标识)为viewController
恢复标识是iOS 为了实现UI状态保持和恢复添加的设置项目。我们还需要在应用程序委托对象AppDelegate代 码部分做一些修改,添加的代码如下:
-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder{
//allow to save UI state when app exit
return YES;
}
-(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder{
//allow to restore UI state when app run
return YES;
}
-(void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder{
//save UI data and state
//save simple data
[coder encodeFloat:2.0 forKey:@"Version"];
}
-(void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder{
//use when restore
//restore data last time save
float lastVer = [coder decodeFloatForKey:@"Version"];
NSLog(@"last Ver = %f",lastVer);
}
想要实现具体界面中控件的保持和恢复,还需要在它的视图控制器中添加一些代码。我们在ViewController.m 中添加的代码如下:
{
[super encodeRestorableStateWithCoder:coder];
[coder encodeObject:self.txtField.text forKey:kSaveKey];
}
-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
[super decodeRestorableStateWithCoder:coder];
self.txtField.text = [coder decodeObjectForKey:kSaveKey];
}
本文介绍如何在iOS应用中实现界面控件的状态保存与恢复功能。通过设置ViewController的RestorationID并添加必要的代码到AppDelegate及ViewController中,可以确保即使在应用退出后重新启动时,界面元素如文本框仍能保留其原始状态。
723

被折叠的 条评论
为什么被折叠?



