[英]Can't set UIImage to UIImageView from Url?
I can't understand why I can't set the uimageview from url from the example below: 我不明白为什么我不能从以下示例的URL中设置uimageview:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://a4.mzstatic.com/us/r30/Music/08/e9/14/mzi.lmcnwrii.60x60-50.jpg"]];
UIImage *image = [UIImage imageWithData:data];
self.imgAlbum1 = [[UIImageView alloc] initWithImage:image];
it works fine by browsing the image, IBOutlet is ok, even setting uiimage from imagenamed doesn't work 通过浏览图像可以正常工作,IBOutlet正常,即使从imagenamed设置uiimage也不起作用
I tried to recreate the contorl in the storyboard but nothing... 我试图在情节提要中重新创建控制,但是什么也没有。
any tips are appreciated 任何提示表示赞赏
Presumably imgAlbum1
is an outlet to your existing image view. 大概
imgAlbum1
是您现有图像视图的出口。
Instead of that last line, which tries to create a new image view without displaying it anywhere, you probably want: 您可能需要:而不是最后一个试图创建新图像视图而不在任何地方显示它的视图,
self.imgAlbum1.image = image;
Edit: If your imgAlbum1
is an IBOutlet
, you probably set it as a WEAK property. 编辑:如果您的
imgAlbum1
是IBOutlet
,则可能将其设置为WEAK属性。 If that is the case, the image will never show up. 在这种情况下,图像将永远不会显示。 In order to use
alloc
, your property would have to be a STRONG property. 为了使用
alloc
,您的属性必须是STRONG属性。
Since you are probably using a WEAK outlet, try using self.imgAlbum1
as the other poster suggested. 由于您可能使用的是
self.imgAlbum1
插座,请尝试使用self.imgAlbum1
作为其他建议的海报。 The reason this will work though, is because you're just updating the image, not the actual imageView
object (weak properties, when you re-alloc will essentially destroy the object completely). 但这之所以起作用,是因为您只是更新图像,而不是实际的
imageView
对象(弱属性,当您重新分配时,本质上将完全破坏该对象)。
This is what I did which I tested and works just fine: 这是我所做的测试,效果很好:
NSString *encodedString = [[NSString stringWithFormat:@"%@", @"us/r30/Music/08/e9/14/mzi.lmcnwrii.60x60-50.jpg"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://a4.mzstatic.com/%@", encodedString]];
NSData *data = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [[UIImage alloc] initWithData:data];
UIImageView *imgAlbum1 = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imgAlbum1];
So the questions for me are: 所以对我来说,问题是:
@property (nonatomic, weak) IBOutlet *imgAlbum1)
? @property (nonatomic, weak) IBOutlet *imgAlbum1)
? If so, don't set it to strong - rather, just use self.imgAlbum1.image = image;
self.imgAlbum1.image = image;
imgAlbum1
an IBOutlet
to a UIImageView
? imgAlbum1
一个IBOutlet
到UIImageView
? If so, is it hidden (or hidden by a layer)? etc. 等等
Otherwise, the code seems fine. 否则,代码看起来很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.