Swift:使用Photos自定义相册

1、在viewDidLoad注册通知

PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)

2、在函数photoLibraryDidChange下添加如下内容

    dispatch_async(dispatch_get_main_queue()) {
        let collectionChanges = changeInstance.changeDetailsForFetchResult(self.allResults)
        if collectionChanges != nil {
            // 是否变化
            if collectionChanges!.hasIncrementalChanges {
                // 监听增加或者删除
                if (collectionChanges!.insertedObjects.count > 0) || (collectionChanges!.removedObjects.count > 0) {
                       self.allResults = collectionChanges?.fetchResultAfterChanges
                       self.photosA = self.allResults
                       self.imageCollectionView.reloadData()
                }
            } else {
                // 首次的时候走这里
                if collectionChanges!.fetchResultBeforeChanges.count == 0 {
                    self.allResults = collectionChanges?.fetchResultAfterChanges
                    self.photosA = self.allResults
                    self.imageCollectionView.reloadData()
                }
            }
        }
    }  

3、在cellForItemAtIndexPath里显示自定义的CollectionView

   let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellID", forIndexPath: indexPath) as! MyCollectionViewCell
    PHCachingImageManager.defaultManager().requestImageForAsset(PCommon.photosA![PCommon.photosA!.count - indexPath.row - 1] as! PHAsset, targetSize: CGSizeZero, contentMode: .AspectFit, options: nil) { (result: UIImage?, dictionry: Dictionary?) in
        cell.imageView.image = result ?? UIImage.init(named: "默认的图片")
    }

至此,照片就很方便的展示在自定义的CollectionView中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容