2014-02-18 33 views
1

我正在通過點擊按鈕添加UIImageView。我想用UIKit來恢復它。 我得到恢復標識符:狀態保存和恢復UIImageView添加自按鈕事件

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

我如何可以解碼此UIImageView

+0

你應該編碼和解碼圖像不ImageView的。在恢復狀態的過程中。 – Pawan

+0

imageview不是在我的.h文件中,也不在xib文件中。我正在製作並添加該圖像查看按鈕click.i需要重建imageview? – user1780632

+0

有一個解決方案。你必須做一個圖像集合。編碼和解碼這個集合。你應該嘗試一下你自己。 – Pawan

回答

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

} 
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

+0

我從代碼添加imageview它沒有在我的頭文件中初始化 – user1780632

+0

你認爲,沒有將uiimage轉換成nsdata,你可以編碼和解碼它。 – Pawan

+0

按鈕點擊 我用這樣做 – user1780632