Firstly, thank you user3339357 for all your help. You gave me the basis to my final solution.
Solution:
I adjusted the scrollViewDidScroll:
function as follows, in order to create missing images and release images that were no longer needed:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//Get the frame that the scroll view is currently showing
CGRect visibleF = [scrollView convertRect:scrollView.bounds toView:scrollView.contentView];
//Loop through all territories and determine which need to be rendered
for (int i = (int)territoryArray.count - 1; i >= 0; i--) {
//Put the following in an autoreleasepool to conserve memory
@autoreleasepool {
//See if the territory is on-screen
if (CGRectIntersectsRect(visibleF, [[territoryArray objectAtIndex:i] frame])) {
//See if the territory needs an image
if ([[territoryArray objectAtIndex:i] image] == nil) {
//Set the territory's image
[[territoryArray objectAtIndex:i] setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@T%i.png", [defaults objectForKey:@"Current_Map"], i + 1] ofType:nil]]];
//Update the territory's color
[self updateColorOnTerritory:[territoryArray objectAtIndex:i]];
}
} else {
//Remove the territory's image, it is off-screen
[[territoryArray objectAtIndex:i] setImage:nil];
}
}
}
}
Essentially, the code gets the visible frame of the scroll view's content view (the line of code that creates visibleF
allows for scaling/zooming on the scroll view as well). The program then loops through an array that holds a reference to each Territory
object in the scroll view and determines which territories should be visible, and sets their images if they don't exist. It also resets image views that are not currently visible on the screen.
It should be noted that I adjusted the OBShapedButton
library and changed it so that it's a subclass of UIImageView
since I was having issues forcing buttons to release memory that they were no longer using. I used UITapGestureRecognizer
s in place of IBAction
s.
EDIT:
The code above was causing lag in the scroll view (a lot of it). I solved this problem by adding the following code in the MapScrollView
subclass I made for the UIScrollView
:
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return NO;
}
Hope this helps anyone else with a similar problem!