如何在scrollview中的dispatch_async方法中获取图像的动态高度
问题描述:
我正在使用下面的代码从服务器获取图像。我想获得图像的动态高度并在滚动视图中添加图像。如何在scrollview中的dispatch_async方法中获取图像的动态高度
从下面的代码,当我得到dispatch_async方法外的高度,它显示为零。
我怎样才能获得与异步图像加载的图像的动态高度。
- (void)viewDidLoad {
[self LoadViewPublicEvents];
}
-(void) LoadViewPublicEvents
{
for (int i=0;i<arrayPublicEvents.count;i++)
{
UIImageView *img_vw1=[[UIImageView alloc] init];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://abc.us/uploads/event/%@",[[arrayPublicEvents objectAtIndex:i] valueForKey:@"image"]]]];
UIImage *images = [[UIImage alloc]initWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
img_vw1.image = images;
scaledHeight = images.size.height;
});
});
NSLog(@"%f",scaledHeight); // it print zero
img_vw1.backgroundColor=[UIColor clearColor];
img_vw1.frame=CGRectMake(0,y+5,screen_width,197);
[img_vw1 setContentMode:UIViewContentModeScaleAspectFit];
img_vw1.backgroundColor=[UIColor clearColor];
[self.scrll_vw addSubview:img_vw1];
}
}
在此先感谢
答
您的代码:
NSLog(@"%f",scaledHeight); // it print zero
img_vw1.backgroundColor=[UIColor clearColor];
img_vw1.frame=CGRectMake(0,y+5,screen_width,197);
[img_vw1 setContentMode:UIViewContentModeScaleAspectFit];
img_vw1.backgroundColor=[UIColor clearColor];
[self.scrll_vw addSubview:img_vw1];
正在执行,您加载图像之前。
因此,您必须等待(因此您可以使用信号量,直到线程完成),或者将其放入块中。
至于要修改它是有道理的将其放置到主块中的UI:
UIImageView *img_vw1=[[UIImageView alloc] init];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://abc.us/uploads/event/%@",[[arrayPublicEvents objectAtIndex:i] valueForKey:@"image"]]]];
UIImage *images = [[UIImage alloc]initWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
img_vw1.image = images;
scaledHeight = images.size.height;
NSLog(@"%f",scaledHeight); // it print zero
img_vw1.backgroundColor=[UIColor clearColor];
img_vw1.frame=CGRectMake(0,y+5,screen_width,197);
[img_vw1 setContentMode:UIViewContentModeScaleAspectFit];
img_vw1.backgroundColor=[UIColor clearColor];
[self.scrll_vw addSubview:img_vw1];
});
});
欲了解更多信息,这里是苹果公司的文档的链接:https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html
dispatch_async(dispatch_get_main_queue() ,^ { img_vw1.image = images; }); Lepidopteron
现在查看我的编辑代码。我需要如何使用高度变量@Lepidopteron – diksha