UIImage imageNamed
I'm trying to use a url as a UIImage
in the OpenFlow API.
NSString *imageUrl = [[[newsEntries objectAtIndex:0] objectForKey: @"still"] retain];
NSURL *url2 = [NSURL URLWithString:imageUrl];
NSData *photoData = [NSData dataWithContentsOfURL:url2];
UIImage *imageUI = [UIImage imageWithData:photoData]
UIImageView *myImage = [UIImageView initWithFrame:imageUI];
[(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:myImage]];
[imageUr release];
[(AFOpenFlowView *)self.view setNumberOfImages:3];
I have tried it like this, but no success. The only way I got this API working was using the imageNamed
type. The initwithData
has no success.
So how can I change this NSString
to finally become a imageNamed
method?
A UIImageView is different from a UIImage.
Change this line: [(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:myImage]];
To this: [(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:imageUI]];
and it should work.
You have several significant errors here. It appears that you may need to read about C/Objective-C and types.
It sounds like you are asserting that, specifically, the line
UIImage *imageUI = [UIImage imageWithData:photoData]
is not working. The code up to that point actually looks okay (though it is not necessary to retain and then release the imageUrl
variable.
Once you have created your UIImage
, you should be able to pass it directly to your AFOpenFlowView
:
[(AFOpenFlowView*)self.view setImage:imageUI forIndex:0];
The line
UIImageView *myImage = [UIImageView initWithFrame:imageUI];
has two errors (and is unnecessary anyway). First, -initWithFrame
takes a CGRect
as its argument, not a UIImage
. UIImageView
does have an initialization method -initWithImage
, which is probably what you intended. But either way, methods that start with "init" are instance methods, not class methods, so you have to call them on actual instances of a UIImageView
, like this:
UIImageView *myImage = [[UIImageView alloc] initWithImage:imageUI];
Note that this will leak memory unless you autorelease or release it.
The following line, you correctly try to give a UIImage
to your AFOpenFlowView
, but you attempt to create that UIImage
by passing a UIImageView
to the +imageNamed
method. +imageNamed
takes an NSString that contains the name of the image, and passing anything else to it won't work.
You must always be aware of what kind of object a method is expecting to receive, and make sure you find some way to give it that kind of thing.
Probably what you are looking for here is something like this:
NSString *imageUrl = [[newsEntries objectAtIndex:0] objectForKey: @"still"];
NSString *imageName = [imageUrl lastPathComponent];
[(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:imageName]];
精彩评论