When using UITableView, we can reuse its cells using [[ UITableViewCell alloc] initWithStyle: reuseIdentifier:]
and [uiTableViewInstance dequeueReusableCellWithIdentifier:]
methods. This helps keep memory in check for huge tables as only a few cells are there in the view at a given instant.
I want to create a UIScrollView
that has many subviews. Inserting all the subviews takes up a lot of memory and initial time that I want to avoid. Does Apple API provides ways to reuse such custom components (a UIView or a subclass of it here) just like cell views using a identifier?
I will create one if there is no API, but have some doubts regarding this. For example, for every new subview, I am setting its frame position, after the previos views. How should I go about updating the frame for each subview while recycling? Should I delete and reload the content of every subview as it gets recycled? Should I do all these calculations in another thread to avoid jerky scrolling? In all, I would like to have a smooth scrolling experience like in UITableView with all the reusing stuff.
Here is a sample of code that I have written so far:
int numberOfPages = 0;
int pageWidth = 100;
int pageHeight = 100
UIScrollView *myScrollView = //allocate and initialize a scrollview
//set its size to 100 by 100 (width equal to pageWidth)
//set paging enabled for myScrollView
Adding subviews to it from a method, that is called multiple times
- (void) appendSubViewToScrollView {
UIView *view = //allocate and initialize a view and dump data in it.
CGRect rect = view.frame;
rect.size.height = pageHeight;
rect.size.width = pageWidth;
rect.origin = CGPointMake(pageHeight * numberOfPages, 0);
view.frame = rect;
[myScrollView addSubview:view];
numberOfPages++;
[scrollView setContentSize:CGSizeMake(pageHeight * numberOfPages, pageWidth)];
[view release];
}
Edit:
Some insight into how tableview and its cells achieve this behind the scenes would be useful.