2017-02-12 38 views
0

我想知道動態調整UICollectionViewCell的尺寸的最佳方式(SWIFT 3)。我有異步圖像上傳到一個ViewController,它爲UICollectionView實現適當的協議。圖像將全部是不同的大小,所以我需要在加載UIImageView數據後設置單元格的尺寸。我打開collectionview本身的佈局選項,但首先我想獲得正確的單元格尺寸。動態上漿UICollectionViewCell與動態圖像上傳斯威夫特

我知道有類似於幾個帖子了,但我想知道最適當的方式在斯威夫特3做到這一點,我不能完全找到正確的方法呢。

是否有可能做的func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {}方法動態調整?或者,在加載整個視圖時是否可以設置自動調整大小選項?

這是我此刻的相關方法,該的CollectionView的所有靜態大小:

override func viewDidLoad() { 
     super.viewDidLoad() 
     ExitNameLabel.text = exitName 
     let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout() 
     layout.itemSize = CGSize(width: 120 , height: 120) 
     self.imagesCollectionView.setCollectionViewLayout(layout, animated: true) 
     exitLocationDetails.text = exitLocation 
     imagesCollectionView.delegate = self 
     imagesCollectionView.dataSource = self 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    { 
     return imageUrls.count 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell:ImageCollectionViewCell = imagesCollectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell 

     if (images_cache[imageUrls[indexPath.row]] != nil) { 
      cell.imageCell.image = images_cache[imageUrls[indexPath.row]] 
     } else { 
      loadImage(imageUrls[indexPath.row], imageview:cell.imageCell) 
     } 
     return cell 
    } 


    func numberOfSections(in collectionView: UICollectionView) -> Int { 
     return 1 
    } 

    func collectionView(collectionView: UICollectionView, 
         layout collectionViewLayout: UICollectionViewLayout, 
         sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
     let screenSize: CGRect = UIScreen.main.bounds 
     let width = screenSize.width 
     return CGSize(width: CGFloat(width), height: imagesCollectionView.bounds.size.height) 
    } 

感謝您的幫助了一款iOS新手:)

回答

1

試試這個

if (images_cache[imageUrls[indexPath.row]] != nil) { 
    cell.imageCell.image = images_cache[imageUrls[indexPath.row]] 
    cell.imageCell.contentMode = .scaleAspectFit 
} else { 
    loadImage(imageUrls[indexPath.row], imageview:cell.imageCell) 
} 
+0

啊!我想到了。這適用於圖像已被緩存或下載的情況。我需要的是在圖像加載完成後調用'self.imagesCollectionView.reloadData()'。謝謝! – jeanmw