How can I replace the imageView in a UITableViewCell?
I have a type that inherits from UIImageView but adds some extra functionality. I'd like to put it into my UITableViewCells as the image view, but would rather not do a whole new cell layout just so that I can add this image.
When I try to set the image view directly (self.imageView = myImageView
) I get a compile error telling me that imageView is readonly. Is there any way around this or do I need to write a new table view cell class?
For greater clarity:
@interface MyImageViewClass : UIImag开发者_高级运维eView {
}
@end
==========================
@interface MyTableCellClass : UITableViewCell {
}
@end
@implementation MyTableCellClass
-(void) setupCell
{
MyImageView *imageView = [[[MyImageView alloc] init] autorelease];
self.imageView = imageView; // <---- THIS THROWS A COMPILE ERROR
}
@end
There are several options here.
You can just insert your own image view into the cell at the same location as the normal image view. In
tableView:willDisplayCell:forRowAtIndexPath:
, you can set the frame of your image view to match the default one (so you'll get Apple's layout logic). Then just set the image for your image cell rather than the default one.You can do the same, but "steal" the image in
tableView:willDisplayCell:...
. Just setmyImageView.image=imageView.image
and clear theimageView
's image. This would make it more transparent but slightly more magical.Get fancy and ISA swizzle the
imageView
to your class. You must have no additional ivars or synthesized properties in your class for this to work or the crashes you get will be bizarre. Search around for "isa swizzle" or "class swizzle."
Just tell me if I'm wrong, but a "self." property reference returns a getter and a setter for a variable of that class, correct? Aren't you effectively saying in your code, imageView = imageView?
Try changing the name of MyImageView *imageView to imageView2. Even if it doesn't fix the problem, it prevents a potential confusion.
You would do this:
self.imageView.image = myImage;
or:
[self.contentView addSubview:myImageView];
精彩评论