2014-09-10 247 views
3

嗨我有一個陣列與100張圖片url從flickr採取。當我使用UICollectionView我顯示100個細胞中,只有8個細胞是在屏幕上,當我向下滾動才能看到未來8他們像以前一樣,當我執行Swift - UICollectionView重複(重複)單元格

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! 

和println(「東西」)它在控制檯只寫8次的東西,但陣列的含量爲100

我用這個:

func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int { 
    return self.photosUrls.count 
} 

它使100個細胞,但細胞總是重複...任何人誰知道如何擊敗斯威夫特在XCode GM種子的新版本中?

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! { 
    let cell: ImageCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as ImageCell 
    let imgUrl = photosUrls[indexPath!.row] 
    let api_url = NSURL.URLWithString(imgUrl) 
    let URLReq = NSURLRequest(URL: api_url) 
    let NSOpQ:NSOperationQueue = NSOperationQueue() 
    NSURLConnection.sendAsynchronousRequest(URLReq, queue: NSOpQ, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
     if(error == nil){ 
      cell.theWPImage!.image = UIImage(data: data) 
     } 
     }) 
    return cell 
} 

回答

2

我想你不瞭解UITableViewUICollectionView委託方法是如何工作的。

iOS不會同時加載100個單元格,因爲它會非常緩慢,而且用戶體驗不佳。因此,只有當單元格出現在屏幕上時纔會調用方法cellForItemAtIndexPathcellForRowAtIndexPath

每當您向下滾動時,您都會看到再次調用方法cellForItemAtIndexPath以製作新的單元格。如果將代碼println(indexPath.row)置於cellForItemAtIndexPath之內,則實際上會看到在向上或向下滾動時重複打印的單元格編號。

如果在向下滾動後看到相同的單元格,則可能是由於代碼爲cellForItemAtIndexPath。除非您粘貼上面的完整源代碼,否則我無法爲您提供幫助。或者它可能是XCode GM種子UICollectionView中的一個錯誤。

如何在XCode 6 Beta 7中嘗試相同的項目並回報?我在XCode GM中也遇到了UICollectionView問題。 IT與約束有關。請參閱:iOS 8 GM does not update constraints on collection views我現在正在使用XCode 6 Beta 7。

+0

我添加了代碼。看到它,謝謝:) – 2014-09-11 08:01:22

1

你的問題是你正試圖加載cellForRow函數內的圖像。在圖片下載的時候,你的collectionView會顯示另一個單元格。 正確的做法之一是將viewDidLoad中的圖像加載到數組中,然後從cellForRow中的數組中加載該數組。