保存多个自定义UIImageViews

时间:2011-12-12 13:45:35

标签: objective-c uiimageview persistence nskeyedarchiver

我最近正在检查“演示照片板”项目here

这是一个简单的演示,将UIImageViews添加到添加了UIGestureRecognizers的屏幕上......允许用户操作各种UIImageViews。

我像这样添加视图:

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];


imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
imageview.userInteractionEnabled = YES;
[imageview setImage:image];

UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
[pinchRecognizer setDelegate:self];
[imageview addGestureRecognizer:pinchRecognizer];

UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
[rotationRecognizer setDelegate:self];
[imageview addGestureRecognizer:rotationRecognizer];

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[imageview addGestureRecognizer:panRecognizer];


[self.view addSubview:imageview];  }

我甚至可以像这样保存视图:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:imageview] forKey:@"imageViewSaved"];

现在我的问题:以下方法仅保存添加到屏幕的最后一个图像视图。任何人都知道如何保存屏幕上的所有图像视图...如果用户添加多个图像视图?

2 个答案:

答案 0 :(得分:0)

我真的不认为你想将整个UIImageView对象保存到用户默认值。相反,尝试保存UIImage对象的列表,这将更轻量级。 (序列化更有意义。)

你可以这样做:

NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSArray *savedArray = [defs objectForKey:@"SAVED_IMAGES"];
// Create a mutable version in case the serialized copy is an NSArray
NSMutableArray *mutableImages = savedArray ? [NSMutableArray arrayWithArray:savedArray] : [NSMutableArray array];
[mutableImages addObject:image];
[defs setObject:mutableImages forKey:@"SAVED_IMAGES"];
[defs save];

答案 1 :(得分:0)

要区分屏幕上的UIImageViews,您可以执行以下操作。

定义开始ImageView标签号

#define kImageViewTag 3000

为添加到屏幕的图像数定义实例var。

NSUInteger numberOfImage = 0

每当您创建一个新的UIImageView时,请增加计数并使用kImageViewTag添加它并将其分配给tag属性。

imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
imageview.userInteractionEnabled = YES;
[imageview setImage:image];
numberOfImage += 1;
imageView.tag = kImageViewTag + numberOfImage;

每当您枚举屏幕子视图时,如果该类是带有标记> = kImageViewTag的UIImageView,您就知道这些是从UIImagePickerController添加到屏幕的图像。