如何在scrollview中的dispatch_async方法中获取动态高度的图像

时间:2017-04-07 12:02:48

标签: objective-c ios9 ios10

我使用下面的代码从服务器获取图像。我想获得动态的图像高度,并在scrollview中添加图像。

从下面的代码中,当我在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];

   }
}

提前致谢

1 个答案:

答案 0 :(得分:0)

您的代码:

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];
        });

   });

有关详细信息,请参阅Apple的文档链接:https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html