簡體   English   中英

Swift3:如何在UICollectionView中獲取圖像?

[英]Swift3: How to get images in UICollectionView?

我是swift3的初學者,在從UICollectionView中獲取圖像時遇到問題。 我按照本教程( https://github.com/zhangao0086/DKImagePickerController )從照片庫上傳多個圖像,但是我不知道如何從UICollectionView中檢索圖像。

UICollectionView的屏幕截圖

來自ViewController的代碼

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let asset = self.assets![indexPath.row]
    var cell: UICollectionViewCell?
    var imageView: UIImageView?

    if asset.isVideo {
        cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellVideo", for: indexPath)
        imageView = cell?.contentView.viewWithTag(1) as? UIImageView
    } else {
        cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellImage", for: indexPath)
        imageView = cell?.contentView.viewWithTag(1) as? UIImageView
    }

    if let cell = cell, let imageView = imageView {
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        let tag = indexPath.row + 1
        cell.tag = tag
        asset.fetchImageWithSize(layout.itemSize.toPixel(), completeBlock: { image, info in
            if cell.tag == tag {
                imageView.image = image
            }
        })
    }

    return cell!
}

任何幫助深表感謝。

非常感謝你!

根據您的要求,您可以執行類似的操作以從collectionView獲取圖像。

var imagesArray = [UIImage]()
for i in (0...collectionView.numberOfItems(inSection: 0)) {
        let indexPath = IndexPath.init(row: i, section: 0)
        let cell = collectionView(collectionView, cellForItemAt: indexPath)
        let imageView = cell.viewWithTag(11) as! UIImageView
        let image = imageView.image
        imagesArray.append(image!)
}

我建議您從資產庫中獲取圖像。 因為這一行代碼let cell = collectionView(collectionView, cellForItemAt: indexPath)有效地完成了同樣的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM