如何使UIImageView
加载图像,但URL在UILabel
上?
更多的解释:我有一个UILabel
包含一个图像web地址,所以我想要这个地址加载UIImageView
上的图像。我想它涉及一些编码,但我不知道如何做到这一点。请帮助!
UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:yourlabel.text]]];
将上面的图片添加到你的UIImageView:
UIImageView *img = [[UIImageView alloc] initWithImage:myImage];
编辑:到这里阅读"类别"部分。这里的示例方法检查字符串是否是带有http://前缀的URL。使用它,如果它返回NO,只需添加字符串"http://"作为前缀yourlabel。文本,然后传递到上面,而不是yourlabel.text
如链接所示,这只是基本的URL检测验证字符串是否有http://
前缀示例代码:一个简单的基于窗口的应用程序
- (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;
}
这比你想象的要容易。
首先,将URL字符串转换为NSURL
NSURL* imageUrl = [NSURL URLWithString:url];
然后在该URL加载数据
NSData* imageData = [NSData dataWithContentsOfURL:imageUrl];
然后将数据加载到UIImage
UIImage* image = [UIImage imageWithData:imageData];
最后,告诉你的UIImageView显示那个图像
imageView.image = image;