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

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

问题描述:

我正在通过点击按钮添加UIImageView。我想用UIKit来恢复它。 我得到恢复标识符:状态保存和恢复UIImageView添加自按钮事件

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

我如何可以解码此UIImageView

+0

你应该编码和解码图像不ImageView的。在恢复状态的过程中。 – Pawan

+0

imageview不是在我的.h文件中,也不在xib文件中。我正在制作并添加该图像查看按钮click.i需要重建imageview? – user1780632

+0

有一个解决方案。你必须做一个图像集合。编码和解码这个集合。你应该尝试一下你自己。 – Pawan

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

这里是编码&解码过程

-(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]; 

} 

使状态保存和恢复工作有一些总是需要两个步骤:

  • 应用程序的委托必须进行选择
  • 每个视图控制器或视图是 保存/恢复必须有分配的恢复标识符。

对于需要保存和恢复状态的视图和视图控制器,您还应该实现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

+0

我从代码添加imageview它没有在我的头文件中初始化 – user1780632

+0

你认为,没有将uiimage转换成nsdata,你可以编码和解码它。 – Pawan

+0

按钮点击 我用这样做 – user1780632