swift 相册的自定义

用 swift写的相册自定义,将相册里面的所有图片取出,然后在自定义的页面显示,用这个方法可以写相册图片的多张选择,相册的样式自定义。

代码部分:

import UIKit
import Photos

class ImgPickerVC: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{

    @IBOutlet weak var collectionView: UICollectionView!
    //var collectionView:UICollectionView?
    
    ///取得的资源结果,用了存放的PHAsset
    var assetsFetchResults:PHFetchResult<AnyObject>!
    //var fetchResults:PHFetchResult!
    ///缩略图大小
    var assetGridThumbnailSize:CGSize!
    
    /// 带缓存的图片管理对象
    var imageManager:PHCachingImageManager!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //initCollectionView()
        
        //则获取所有资源
        let allPhotosOptions = PHFetchOptions()
        //按照创建时间倒序排列
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                             ascending: false)]
        //只获取图片
        allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
        
        //assetsFetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: allPhotosOptions)
        let fetchResults:PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: allPhotosOptions)
        self.assetsFetchResults = fetchResults as! PHFetchResult <AnyObject>
        debugPrint("get all img",fetchResults)
        // 初始化和重置缓存
        self.imageManager = PHCachingImageManager()
        self.resetCachedAssets()
        
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection =  UICollectionViewScrollDirection.vertical
        let itemWidth = UIScreen.main.bounds.size.width/4 - 6
        let itemHeight:CGFloat = 100.0
        flowLayout.itemSize = CGSize(width: itemWidth , height: itemHeight)
        flowLayout.minimumLineSpacing = 2 //上下间隔
        flowLayout.minimumInteritemSpacing = 2 //左右间隔
        //self.collectionView?.collectionViewLayout = flowLayout
        
        //self.collectionView =  UICollectionView(frame: CGRect(x:0, y:49, width:UIScreen.main.bounds.size.width, height:UIScreen.main.bounds.height-49), collectionViewLayout: flowLayout)
        self.collectionView.collectionViewLayout = flowLayout
        
        /**regist collectionCell*/
        self.collectionView?.register(ResultCollectionCell.self, forCellWithReuseIdentifier: "resultCollectIdentifer")
        
        self.collectionView?.backgroundColor = UIColor.white
        
        self.view.addSubview(self.collectionView!)
        //设置代理
        self.collectionView?.delegate = self
        self.collectionView?.dataSource = self
        
        //根据单元格的尺寸计算我们需要的缩略图大小
        let scale = UIScreen.main.scale
        let cellSize = flowLayout.itemSize
        assetGridThumbnailSize = CGSize( width:cellSize.width*scale , height:cellSize.height*scale)

    }

    //重置缓存
    func resetCachedAssets(){
        self.imageManager.stopCachingImagesForAllAssets()
    }
    
    func initCollectionView(){
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection =  UICollectionViewScrollDirection.vertical
        let itemWidth = UIScreen.main.bounds.size.width/4 - 6
        let itemHeight:CGFloat = 100.0
        flowLayout.itemSize = CGSize(width: itemWidth , height: itemHeight)
        assetGridThumbnailSize = flowLayout.itemSize
        flowLayout.minimumLineSpacing = 2 //上下间隔
        flowLayout.minimumInteritemSpacing = 2 //左右间隔
        //self.collectionView =  UICollectionView(frame: CGRect(x:0, y:49, width:UIScreen.main.bounds.size.width, height:self.view.bounds.height), collectionViewLayout: flowLayout)
        self.collectionView?.collectionViewLayout = flowLayout
        self.collectionView?.backgroundColor = UIColor.white
        
        /**regist collectionCell*/
        self.collectionView?.register(ResultCollectionCell.self, forCellWithReuseIdentifier: "resultCollectIdentifer")
        //注册
        //self.collectionView?.register(ZuberImageCell.self,forCellWithReuseIdentifier:"cell")
       
    }

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.assetsFetchResults!.count
        //return 9
    }
    
    
    
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        /**加载cell*/
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "resultCollectIdentifer", for: indexPath) as! ResultCollectionCell
        
        cell.backgroundColor = UIColor.red
        
        let asset = self.assetsFetchResults?[indexPath.row] as! PHAsset
        self.imageManager.requestImage(for: asset, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil) { (img, info) in
            cell.imgView?.image = img
        }
        debugPrint("get asset img",asset)
        
        return cell
    }

    
    @IBAction func cancleHandle(_ sender: AnyObject) {
        
        self.dismiss(animated: true, completion: nil)
        debugPrint("取消图片选择")
    }
    
    @IBAction func confirmHandle(_ sender: AnyObject) {
        
        self.dismiss(animated: true, completion: nil)
        debugPrint("确认图片选择")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

这里有个问题还没有解决,就是不允许访问相册的时候,程序会死掉。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值