如何在Swift

时间:2019-06-17 04:18:20

标签: ios swift uicollectionview uicollectionviewcell

产生类似于Twitter上传页面的最佳方法是什么,该页面显示约10张照片库图片供用户选择?

下面是我正在尝试做的图片。

这是我到目前为止所做的。但是,当我运行该应用程序时,它不会显示。

import photos

class UploadPostVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    var imageArray = [UIImage]()

    @IBOutlet weak var showPhotosCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        grabPhotos()
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

        let imageView = cell.viewWithTag(1) as! UIImageView

        print("wassup")
        imageView.image = self.imageArray[indexPath.row]

        return cell
    }

    func grabPhotos(){
        let imgManager = PHImageManager.default()

        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = true
        requestOptions.deliveryMode = .highQualityFormat

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
            if fetchResult.count > 0 {
                for i in 0..<fetchResult.count{

                    //Used for fetch Image//
                    imgManager.requestImage(for: fetchResult.object(at: i) as PHAsset , targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: requestOptions, resultHandler: {
                        image, error in
                        let image = image! as UIImage
                        self.imageArray.append(image)
                        self.showPhotosCollectionView.reloadData()
                        print ("appended images")
                    })

                    self.showPhotosCollectionView.reloadData()

                }

            }
            else {
                  print("you got no phots")
                self.showPhotosCollectionView.reloadData()
        }
    } 

what I'm trying to do

1 个答案:

答案 0 :(得分:1)

您应设置集合视图的delegatedataSource。只需更改您的viewDidLoad函数:

override func viewDidLoad() {
    super.viewDidLoad()
    self.showPhotosCollectionView.delegate = self
    self.showPhotosCollectionView.dataSource = self
    grabPhotos()
}