2017-04-07 39 views
0

我正在使用下面的代碼從服務器獲取圖像。我想獲得圖像的動態高度並在滾動視圖中添加圖像。如何在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]; 

    } 
} 

在此先感謝

+0

dispatch_async(dispatch_get_main_queue() ,^ { img_vw1.image = images; }); <---只需使用CGFloat height = images.size.height擴展此塊(或者甚至是異步部分); – Lepidopteron

+0

現在查看我的編輯代碼。我需要如何使用高度變量@Lepidopteron – diksha

回答

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

    }); 

欲瞭解更多信息,這裏是蘋果公司的文檔的鏈接:https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

相關問題