状态保存和恢复UIImageView从按钮事件添加

时间:2014-02-18 19:47:04

标签: objective-c ios6 ios7 uikit-state-preservation

我在点击按钮时添加了UIImageView。我想使用UIKit恢复它。 我正在获取恢复标识符:

 - (void)decodeRestorableStateWithCoder:(NSCoder *)coder;

如何解码此UIImageView

2 个答案:

答案 0 :(得分:1)

要进行状态保存和恢复工作,总共需要两个步骤:

  • 应用代表必须选择加入
  • 每个视图控制器或视图 保留/恢复必须已分配恢复标识符。

您还应该为视图实现encodeRestorableStateWithCoder:decodeRestorableStateWithCoder:,并查看需要保存和恢复状态的控制器。

将以下方法添加到UIImageView的视图控制器中。

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
    [coder encodeObject:UIImagePNGRepresentation(_imageView.image)
                 forKey:@"YourImageKey"];

    [super decodeRestorableStateWithCoder:coder];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    _imageView.image = [UIImage imageWithData:[coder decodeObjectForKey:@"YourImageKey"]];

    [super encodeRestorableStateWithCoder:coder];
}

状态保存和恢复是一项可选功能,因此您需要通过实现两种方法让应用程序委托加入:

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

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

关于国家保护的有用文章: http://useyourloaf.com/blog/2013/05/21/state-preservation-and-restoration.html

答案 1 :(得分:1)

我在我的一个应用中使用了这段代码。

这里是编码&解码过程

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{

NSData *imageData=UIImagePNGRepresentation(self.imgViewProfilePicture.image);
[coder encodeObject:imageData forKey:@"PROFILE_PICTURE"];
[super encodeRestorableStateWithCoder:coder];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{

self.imgViewProfilePicture.image=[UIImage imageWithData:[coder decodeObjectForKey:@"PROFILE_PICTURE"]];
[super decodeRestorableStateWithCoder:coder];

}