您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 網路請求圖片並加上載入動畫的實作

編輯:iOS 技巧大全
[摘要]本文示範如何在 iOS 中透過網路請求載入圖片,並在載入過程中加入 UIActivityIndicatorView 轉圈動畫,提升使用者等待時的體驗。

效果圖:

程式碼:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 200, 200)]; imageView.backgroundColor=[UIColor redColor]; [self.view addSubview:imageView]; [self setImageUrlWithActivityIndicator:@"我愛你!" :imageView]; } //網絡請求圖片時,添加loading控件 -(void)setImageUrlWithActivityIndicator:(NSString*)urlString :(UIImageView *)image { if (![urlString isEqualToString:@""]) { // __block UIActivityIndicatorView *activityIndicator = nil; UIActivityIndicatorView *activityIndicator = nil; activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; [image addSubview:activityIndicator]; CGPoint point = CGPointMake(image.frame.size.width/2, image.frame.size.height/2); activityIndicator.center = point; [activityIndicator startAnimating]; [image setImageWithURL:[NSURL URLWithString:[Image_URL stringByAppendingFormat:@"%@",urlString]] placeholderImage:nil success:^(UIImage *image) { NSLog(@"...success code here..."); [activityIndicator stopAnimating]; [activityIndicator removeFromSuperview]; } failure:^(NSError *error) { NSLog(@"... failure code here ..."); [activityIndicator stopAnimating]; [activityIndicator removeFromSuperview]; }]; } } 

這段程式碼的重點在於:在發請求之前先在 imageView 中央放一個轉圈的 activityIndicator 並啟動動畫,等到圖片下載成功或失敗後,再停止動畫並將其移除。這樣一來,使用者在等待圖片載入時就能看到明確的載入提示,避免畫面出現空白而產生困惑。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved