How can I make an 开发者_开发问答UIImageView
load an image, but the URL is on a UILabel
?
More explanation: I have a UILabel
containing an image web address, so I want this address to load an image on the UIImageView
. I suppose it involves some encoding but I have no idea how to do this. Please help!
UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:yourlabel.text]]];
Add the above image on your UIImageView:
UIImageView *img = [[UIImageView alloc] initWithImage:myImage];
EDIT: Go here and read up on the "Categories" section. The sample method there checks if your string is a URL with a http:// prefix to it. Use that and if it returns NO, just add the string "http://" as a prefix to yourlabel.text and then pass it above instead of yourlabel.text
And yes as the link says, its just basic URL detection that just verifies if the string has been prefixed with http://
Sample code: A simple window based app
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UILabel *label = [[UILabel alloc] init];
label.text = @"http://www.arthistoryarchive.com/arthistory/cubism/images/PabloPicasso-Weeping-Woman-with-Handkerchief-1937.jpg";
UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:label.text]]];
UIImageView *img = [[UIImageView alloc] initWithImage:myImage];
img.frame = CGRectMake(0, 0, 768, 1024);
[self.window addSubview:img];
[self.window makeKeyAndVisible];
return YES;
}
It's easier than you think.
First, convert your URL string into an NSURL
NSURL* imageUrl = [NSURL URLWithString:url];
Then load the data at that URL
NSData* imageData = [NSData dataWithContentsOfURL:imageUrl];
Then load that data into a UIImage
UIImage* image = [UIImage imageWithData:imageData];
And finally, tell your UIImageView to display that image
imageView.image = image;
精彩评论