How can I use a string parameter to specify an image for an iPhone table cell?
I have an object MObject
that is currently defined like so:
+ (id)objectWithType:(NSString*)type name:(NSString*)name code:(NSString*)code imageName:(NSString*)imageName
{
UIImage *theImage = [[UIImage alloc] imageNamed:imageName];
MObject *newObject = [[[self alloc] init] autorelease];
newObject.type = type;
newObject.name = name;
newObject.code = code;
return newObject;
}
imageName
is meant to contain the file name of the appropriate image anImage.png
. Once I put that in, I need the UIImage object to be created so that it can be placed in cell.imageView.image
.
I'm 1) unclear on whether the direc开发者_开发百科tion I've started to take (as shown above) is workable, 2) so far clueless as to how I can get this UIImage
into my in my MainViewController
. I really appreciate any help you offer.
I got it! I changed the code shown in my original post to:
+ (id)objectWithType:(NSString*)type name:(NSString*)name code:(NSString*)code imageName:(NSString*)imageName
{
MObject *newObject = [[[self alloc] init] autorelease];
newObject.type = type;
newObject.name = name;
newObject.code = code;
newObject.imageName = imageName;
return newObject;
}
Then I added the following line to cellForRowAtIndexPath:
cell.imageView.image=[UIImage imagedNamed:object.imageName];
And that's all it took!
- (UIImage *)newImageFromResource:(NSString *)filename
{
NSString *str = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:filename]; UIImage *image = [[UIImage alloc] initWithContentsOfFile:str]; return image; }
and Whenever you want to set Image
UIImage *img=[UIImage newImageFromResource:@"xyz.png"];
You can set img wherever you want & dont forget to release img
精彩评论