Created
August 13, 2011 05:08
A subclass of UITableViewCell to allow for images to be added after cell creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface JKTableViewCell : UITableViewCell | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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