lehn0058
lehn0058

Reputation: 20237

How to reuse UIView like UITableViewCell

I have an app that has many instances of the same UIView. Is their a way to reuse a UIView like you can with UITableViewCell? Similar to:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

Upvotes: 5

Views: 2208

Answers (3)

onmyway133
onmyway133

Reputation: 48095

This simple code demonstrates basic pool that dequeue a view if it is not in any hierarchy. For complex use cases, you should need identifiers, lock, ...

Take a look at my gist FTGViewPool

@interface FTGViewPool ()

@property (nonatomic, strong) NSMutableArray *views;
@property (nonatomic, assign) Class viewClass;

@end

@implementation FTGViewPool

- (instancetype)initWithViewClass:(Class)kClass {
    self = [super init];
    if (self) {
        _views = [NSMutableArray array];
        _viewClass = kClass;
    }

    return self;
}

- (UIView *)dequeueView {
    // Find the first view that is not in any hierarchy
    for (UIView *view in self.views) {
        if (!view.superview) {
            return view;
        }
    }

    // Else create new view
    UIView *view = [[self.viewClass alloc] init];
    [self.views addObject:view];
    return view;
}

Upvotes: 0

J2theC
J2theC

Reputation: 4452

I would recommend using NSCache to cache the UIView instances you need to cache. NSCache differs from NSDictionary because it does not copy the key to obtain the value, and it allows some good mechanism to deal with memory. Check the documentation and see if it works for you. I have used this very recently to cache UIPinAnnotationView objects.

Upvotes: 0

AliSoftware
AliSoftware

Reputation: 32681

I suggest you watch session 104 of WWDC'2010 called "Designing Apps with ScrollViews" that explains the reuse mechanism (IIRC).

You can also look at the source of OHGridView in which I implemented this technique: look at the 2nd layoutSubviews method in OHGridView.m where I add unused UIViews in an NSMutableSet I called recyclePool, and then dequeue some UIViews from this recyclePool when I need one.

Upvotes: 4

Related Questions