OGeek|极客世界-中国程序员成长平台

标题: ios - iOS6中使用restoreIdentifier保存UIImageView的状态 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:05
标题: ios - iOS6中使用restoreIdentifier保存UIImageView的状态

我在文档中读到 @property(nonatomic, copy) NSString *restorationIdentifier 能够保留 UIImageView 属性的状态,例如位置、角度、等我尝试添加方法

-(BOOL)applicationUIApplication *)application shouldRestoreApplicationStateNSCoder *)coder
{
    return YES;
}

-(BOOL)applicationUIApplication *)application shouldSaveApplicationStateNSCoder *)coder
{
    return YES;
}

到 View Controller 。我已经在IB中将 View Controller 的恢复ID设置为@"myFirstViewController

我也在 View Controller 中添加了以下方法。

-(void)encodeRestorableStateWithCoderNSCoder *)coder
{
[coder encodeObject:_myImageView.image forKey"UnsavedImage"];
[super decodeRestorableStateWithCoder:coder];
}

-(void)decodeRestorableStateWithCoderNSCoder *)coder
{
_myImageView.image = [coder decodeObjectForKey"UnsavedImage"];
[super encodeRestorableStateWithCoder:coder];
}

我应该在 appDelegate 或 View Controller 中添加前两个方法吗? UIImageView 没有得到保留。这里有什么问题?



Best Answer-推荐答案


要使状态保存和恢复工作,始终需要两个步骤:

您还应该为需要保存和恢复状态的 View 和 View Controller 实现 encodeRestorableStateWithCoder:decodeRestorableStateWithCoder:

将以下方法添加到 UIImageView 的 View Controller 中。

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

    [super decodeRestorableStateWithCoder:coder];
}

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

    [super encodeRestorableStateWithCoder:coder];
}

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

- (BOOL)applicationUIApplication *)application shouldSaveApplicationStateNSCoder *)coder
{
    return YES;
}

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

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

关于ios - iOS6中使用restoreIdentifier保存UIImageView的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15872738/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4