Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Created August 13, 2011 05:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SlaunchaMan/1143494 to your computer and use it in GitHub Desktop.
Save SlaunchaMan/1143494 to your computer and use it in GitHub Desktop.
A subclass of UITableViewCell to allow for images to be added after cell creation
#import <UIKit/UIKit.h>
@interface JKTableViewCell : UITableViewCell
@end
#import "JKTableViewCell.h"
@implementation JKTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[[self imageView] addObserver:self
forKeyPath:@"image"
options:NSKeyValueObservingOptionOld
context:NULL];
}
return self;
}
// The reason we’re observing changes is that if you create a table view cell, return it to the
// table view, and then later add an image (perhaps after doing some background processing), you
// need to call -setNeedsLayout on the cell for it to add the image view to its view hierarchy. We
// asked the change dictionary to contain the old value because this only needs to happen if the
// image was previously nil.
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (object == [self imageView] &&
[keyPath isEqualToString:@"image"] &&
([change objectForKey:NSKeyValueChangeOldKey] == nil ||
[change objectForKey:NSKeyValueChangeOldKey] == [NSNull null])) {
[self setNeedsLayout];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment