Brian
Brian

Reputation: 733

iOS 5 Location of Objects on Screen

I am creating a test app that will add multiple UIImageViews with images. The user will be able to move and rotate these images around. I have the UIGestureRecognizers in place and working, but I need to also keep track of the location of where the user leaves the images on screen. That way if they close the app and come back, where they placed the images will be remembered.

I know I should be using NSUserDefaults for this, but my question is how do I keep track of possibly a very large amount of UIImageView's locations on screen. I assume I need to somehow get the x/y coordinates of them and store that with NSUserDefaults.

Anyone have suggestions of how to do this?

-Brian

Upvotes: 1

Views: 139

Answers (1)

futurevilla216
futurevilla216

Reputation: 992

UIView's have a property subviews. I suggest looping through the array. Here is an example:

NSMutableDictionary *coordinates = [[NSMutableDictionary alloc] init];
for (id subview in view.subviews) {
    if ([subview isKindOfClass:[UIImageView class]]) {
        [coordinates setObject:[NSValue valueWithPoint:subview.frame.origin] forKey:imageViewIdentifier];
    }
}
//store coordinates in NSUserDefaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:coordinates forKey:@"ImageViewCoordinates"];
[userDefaults synchronize];

Instead of storing the entire image view as the key in the coordinates dictionary, you can use some identifier for it to conserve memory. The object is an NSValue, so to get the x/y values from it you can use [[value pointValue] x] or [[value pointValue] y].

Here is an example of reading the data back (and restoring the view back to normal).

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *coordinates = [userDefaults dictionaryForKey:@"ImageViewCoordinates"];
//Key can be any type you want
for (NSString *key in coordinates.allKeys) {
    UIImageView *imageView;
    //Set UIImageView properties based on the identifier
    imageView.frame.origin = [coordinates objectForKey:key];
    [self.view addSubview:imageView];
    //Add gesture recognizers, and whatever else you want
}

Upvotes: 5

Related Questions