// PicPickerViewController.swift
//
//
import UIKit
private let reuseIdentifier = "Cell"
class PicPickerViewController: UICollectionViewController {
// MARK:- 定义属性
private lazy var images : [UIImage] = [UIImage]()
// MARK:- 系统回调的函数
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerNib(UINib(nibName: "PicPickerViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}
}
// MARK:- CollectioView的数据源方法
extension PicPickerViewController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count + 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// 1.创建cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PicPickerViewCell
// 2.给cell设置数据
cell.backgroundColor = UIColor.redColor()
cell.image = indexPath.item <= images.count - 1 ? images[indexPath.item] : nil
cell.delegate = self
return cell
}
}
// MARK:- Cell的代理方法
extension PicPickerViewController : PicPickerViewCellDelegate {
func addPhotoBtnClickFor(cell: UICollectionViewCell) {
// 1.判断照片源是否可用
if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
return
}
// 2.创建照片选择控制器
let ipc = UIImagePickerController()
// 3.设置照片源
ipc.sourceType = .PhotoLibrary
// 4.设置代理
ipc.delegate = self
// 6.弹出控制器
presentViewController(ipc, animated: true, completion: nil)
}
}
// MARK:- UIImagePickerController的代理方法
extension PicPickerViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// 1.取出用户选择的image
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
picker.dismissViewControllerAnimated(true, completion: nil)
return
}
// 2.将图片放入到数组中
images.append(image)
// 3.刷新表格
collectionView?.reloadData()
// 4.退出照片选择控制器
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK:- 自定义CollectionView的Layout
class PicPickerCollectionViewLayout : UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
// 0.定义间距的常量
let itemPadding : CGFloat = 15
let itemWH = (UIScreen.mainScreen().bounds.width - 4 * itemPadding) / 3
// 1.设置布局相关的属性
itemSize = CGSize(width: itemWH, height: itemWH)
minimumInteritemSpacing = itemPadding
minimumLineSpacing = itemPadding
// 2.设置collectionView相关的属性
collectionView?.contentInset = UIEdgeInsets(top: itemPadding, left: itemPadding, bottom: itemPadding, right: itemPadding)
}
}
网友评论