2017-03-01 36 views
0

我的應用程序中有一個工作的UIScroll視圖和本地圖像。然而,我想要的是,我的圖片將從網址下載並存儲在緩存中。我見過幾個類似sdwebimage,翠鳥等的示例庫,但這些示例使用UITableview和單元格。我爲我的滾動視圖使用UIImage數組。我真正想要的是我下載並緩存我的圖像並將它們存儲在Array IconsArray = [icon1,icon2,icon3],其中icon1到icon3是從URL下載的圖像。我將如何做到這一點?任何漂亮的教程或者有足夠的人來向新秀展示一些代碼?如何將URL中的圖像加載到UIImage數組中並在UIScrollView中將它們用於Swift中

在此先感謝

回答

0

如果您正在下載很多圖片,你將有內存問題,和你的工作也將得到扔掉當你的陣列超出範圍,但你可能會想要做什麼,如果你想要實現你提出的解決方案,就是使用字典而不是數組。它會讓您更容易找到您要查找的圖片。所以,你可以實現的字典是這樣的:

var images = [String : UIImage]() 

因爲你可以只使用URL字符串(很容易的解決方案)的密鑰,以便訪問圖像安全應該是這樣的:

let urlString = object.imageUrl.absoluteString //or wherever you're getting your url from 
if let img = self.images[urlString] { 
    //Do whatever you want with the image - no need to download as you've already downloaded it. 
    cell.image = img 
} else { 
    //You need to download the image, because it doesn't exist in your dict 
    ...[DOWNLOAD CODE HERE]... 
    //Add the image to your dictionary here 
    self.images[object.imageUrl.absoluteString] = downloadedImage 
    //And do whatever else you need with it 
    cell.image = downloadedImage 
} 

正如我說,這有一些缺點,但它是你要求的一個快速實現。

+0

謝謝,我會試試! –

相關問題