Objective c 如何在scrollview中的dispatch_async方法中获取图像的动态高度
我使用下面的代码从服务器获取图像。我想获得图像的动态高度,并在scrollview中添加图像 从下面的代码中,当我得到dispatch_async方法之外的高度时,它显示为零 如何使用异步图像加载动态获取图像高度Objective c 如何在scrollview中的dispatch_async方法中获取图像的动态高度,objective-c,ios9,ios10,Objective C,Ios9,Ios10,我使用下面的代码从服务器获取图像。我想获得图像的动态高度,并在scrollview中添加图像 从下面的代码中,当我得到dispatch_async方法之外的高度时,它显示为零 如何使用异步图像加载动态获取图像高度 - (void)viewDidLoad { [self LoadViewPublicEvents]; } -(void) LoadViewPublicEvents { for (int i=0;i<arrayPublicEvents.count;i++) {
- (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];
}
}
-(void)viewDidLoad{
[self-LoadViewPublicEvents];
}
-(无效)LoadViewPublicEvents
{
对于(int i=0;i您的代码:
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];
});
});
有关更多信息,这里有一个指向苹果文档的链接:dispatch\u async(dispatch\u get\u main\u queue(),^{img\u vw1.image=images;});请查看我的编辑代码。我需要如何使用高度变量@Lepidopteron