如何在单元格末尾添加 CollectionView 自定义单元格?

How to add CollectionView custom cell at the end of cell?

我有一组图像,显示在集合视图中,当我单击打开图像选择器的最后一个单元格时,我创建了一个单元格。 -> 可以在该单元格中设置所选图像,并自动添加最后一个新单元格。 (我对此一无所知,请帮忙,谢谢)

集合视图class

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate
{

var imagePicker = UIImagePickerController()
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5"]

@IBOutlet var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - UICollectionViewDataSource protocol

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

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell

   // cell.backgroundColor = UIColor.cyanColor()
    cell.btnSelectImage.setTitle(items[indexPath.row], forState: .Normal)
    cell.btnSelectImage.tag = indexPath.row
    cell.btnSelectImage.addTarget(self,action:#selector(buttonClicked),
                     forControlEvents:.TouchUpInside)
    return cell

}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    if indexPath.row == 0
    {
        // call your alert here
    }
}
func buttonClicked(sender:UIButton)
{
    let alertController: UIAlertController = UIAlertController(title: "Please choose a Picture".localized, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
    let cameraAction = UIAlertAction(title: "Camera".localized, style: UIAlertActionStyle.Default){
        UIAlertAction in
        self.openCamera()
    }
    let gallaryAction = UIAlertAction(title: "Gallery".localized, style: UIAlertActionStyle.Default){
        UIAlertAction in
        self.openGallary()
    }
    let cancelAction = UIAlertAction(title: "Cancel".localized, style: UIAlertActionStyle.Cancel){
        UIAlertAction in
    }
    alertController.addAction(cameraAction)
    alertController.addAction(gallaryAction)
    alertController.addAction(cancelAction)

    if UIDevice.currentDevice().userInterfaceIdiom == .Phone{
        self.presentViewController(alertController, animated: true, completion: nil)
    }
}
//MARK: - UIImagepickercontroller Method  -

func openCamera()
{
    if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil
    {
        imagePicker.allowsEditing = true
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
        imagePicker.showsCameraControls = true
        imagePicker.cameraCaptureMode = .Photo
        imagePicker.takePicture()

        if UIDevice.currentDevice().userInterfaceIdiom == .Phone
        {
            self.presentViewController(imagePicker, animated: true, completion: nil)
        }
    }
    else
    {
        noCamera()
    }
}

func openGallary()
{
    if UIDevice.currentDevice().userInterfaceIdiom == .Phone
    {
       imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        self.presentViewController(imagePicker, animated: true, completion: nil)
       imagePicker.allowsEditing = true
    }
    else
    {
       imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

    }
}
func noCamera()
{
    let alertVC = UIAlertController(title: "ok", message: "Device has no camera".localized, preferredStyle: UIAlertControllerStyle.Alert)
    let okAction = UIAlertAction(title: "OK".localized, style: UIAlertActionStyle.Default, handler: nil)
    alertVC.addAction(okAction)
    presentViewController(alertVC, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{

    let timestamp = Int(NSDate().timeIntervalSince1970)
    let choosenImage = info[UIImagePickerControllerEditedImage] as! UIImage


    var indexPath = NSIndexPath(forRow: 0, inSection: 0)
    let cell  = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

    cell.btnSelectImage.setBackgroundImage(choosenImage, forState: .Normal)


    collectionView.reloadData()

    dismissViewControllerAnimated(true, completion: nil)

}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
    dismissViewControllerAnimated(true, completion: nil)
} 

}

CollcetionViewCell

class MyCollectionViewCell: UICollectionViewCell
{

 @IBOutlet var btnSelectImage: UIButton!

}

-创建图像数组,显示在collectionview

基本上你必须创建一个 item 类型的对象,因为它是你的 collectionview 的数据源,最后将它添加到 item 数组中,然后重新加载 collectionview。

可能您需要在 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) 方法中执行此操作。

编辑:

var items = [UIImage]()

//可能有一些图片对象

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell

   // cell.backgroundColor = UIColor.cyanColor()
   // cell.btnSelectImage.setTitle(items[indexPath.row], forState: .Normal)
   // cell.btnSelectImage.tag = indexPath.row
   // cell.btnSelectImage.addTarget(self,action:#selector(buttonClicked),
                     forControlEvents:.TouchUpInside)
    let choosenImage = items[indexPath.row]
    cell.btnSelectImage.setBackgroundImage(choosenImage, forState: .Normal)
    return cell

}





func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{

   /* let timestamp = Int(NSDate().timeIntervalSince1970)
    let choosenImage = info[UIImagePickerControllerEditedImage] as! UIImage


    var indexPath = NSIndexPath(forRow: 0, inSection: 0)
    let cell  = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

    cell.btnSelectImage.setBackgroundImage(choosenImage, forState: .Normal)
*/
    let choosenImage = info[UIImagePickerControllerEditedImage] as! UIImage
    self.items.append(choosenImage)
    collectionView.reloadData()    
    dismissViewControllerAnimated(true, completion: nil)

}
// MARK:-
var images:[Images]=[]
//MARK:- UICollectionViewDataSource protocol
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
 return self.images.count+1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.row == images.count{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("newCell", forIndexPath: indexPath) as! MyNewCollectionViewCell
return cell 
}
else{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell
// cell.backgroundColor = UIColor.cyanColor()
cell.btnSelectImage.setTitle(images[indexPath.row].image, forState: .Normal)
cell.btnSelectImage.tag = indexPath.row
cell.btnSelectImage.addTarget(self,action:#selector(buttonClicked),
                 forControlEvents:.TouchUpInside)
return cell
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
if indexPath.row == images.count
{
// call the uipicker opening method here.
}}

从 UIImagePickerView 委托接收的图像模型

class Images{
    var image:UIImage?
}

我的方法是让 var 说 itemsCount 初始化为 1 而不是你的 var 项目是一个数组。还有一个图像数组。

var itemsCount = 1
var images = [UIImage]()

// MARK: - UICollectionViewDataSource protocol

func collectionView(collectionView: UICollectionView, numberOfItemsInSection  section: Int) -> Int {
 return self.itemsCount
}

Returncollection视图.

数据源方法中的itemsCount
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
if indexPath.row == self.itemsCount - 1
{
    // call your alert here
}
}

检查选择的 indexPath 是否是最后一个单元格,因为根据您的要求,您需要在单击最后一个单元格时显示 imagePicker。

现在再添加一个单元格,当图像被成功选取时

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{

let timestamp = Int(NSDate().timeIntervalSince1970)
let choosenImage = info[UIImagePickerControllerEditedImage] as! UIImage

//Change 1
var indexPath = NSIndexPath(forRow: self.itemsCount -1, inSection: 0)
self.images.append(choosenImage)
let cell  = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

cell.btnSelectImage.setBackgroundImage(choosenImage, forState: .Normal)
//Change 2

self.itemsCount += 1

collectionView.reloadData()

dismissViewControllerAnimated(true, completion: nil)

}

在代码中进行更改,标记为 更改 1更改 2。 并进行图像缓存,因为在 cellForRowAtIndexPath 中您没有设置图像,新的 dequed 单元格可能有也可能没有图像。此外,图像可能会根据 dequed 单元格而有所不同。要设置标题,您可以使用

 cell.btnSelectImage.setTitle(String(self.itemsCount), forState: .Normal)
 if images.indices.contains(indexPath.row) {
   cell.btnSelectImage.setBackgroundImage(self.images[indexPath.row], forState: .Normal)
 }

最终,插入一个新单元格而不是重新加载整个 collection 视图的成本会更低。

你的单元格没有按顺序填充图像,所以我建议使用字典数据结构而不是数组。在更改时将图像更新到项目字典以获得索引路径,然后重新加载数据。

var items:[Int:Any] = [1: NSNull() , 2: NSNull(), 3: NSNull(), 4: NSNull(), 5: NSNull()]

在委托调用中:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell

    // cell.backgroundColor = UIColor.cyanColor()
    cell.btnSelectImage.setTitle(items[indexPath.row], forState: .Normal)
    cell.btnSelectImage.tag = indexPath.row

    if let choosenImage = items[indexPath.row+1] as? UIImage {
        print(choosenImage)
        cell.btnSelectImage.setBackgroundImage(choosenImage, forState: .Normal)
    } else {
        cell.btnSelectImage.setBackgroundImage(nil, forState: .Normal)
        print("no image exist")
    }

    cell.btnSelectImage.addTarget(self,action:#selector(buttonClicked),
                                  forControlEvents:.TouchUpInside)
    return cell

}

更新图像选择器回调的字典。

let choosenImage = info[UIImagePickerControllerEditedImage] as! UIImage
items.updateValue(choosenImage, forKey: yourIndexPath)

请仅编辑方法并添加一些方法:

var imagePicker = UIImagePickerController()
var selectedImage : UIImage?

override func viewDidLoad() {
    super.viewDidLoad()
    imagePicker.delegate = self
   // Do any additional setup after loading the view, typically from a nib.
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell

    cell.btnSelectImage.setTitle(items[indexPath.row], forState: .Normal)
    cell.btnSelectImage.addTarget(self,action:#selector(buttonClicked),
                 forControlEvents:.TouchUpInside)

    cell.btnSelectImage.setBackgroundImage(selectedImage, forState: .Normal)//setBackground image of button
    return cell
}


func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    //because need open imagePicker only last cell
    //IF YOU WANT TO OPEN IMAGEPICKER CLICK ON BUTTON THEN ADD COMMENT BELOW LINE
    if indexPath.row == self.items.count-1 
    {
        self.configuringImagePickerController()
    }
}

func buttonClicked(sender:UIButton)
{
   self.configuringImagePickerController()//If you want open imagepicker click on button
}

func configuringImagePickerController()
{
    let alertController: UIAlertController = UIAlertController(title: "Please choose a Picture".localized, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
    let cameraAction = UIAlertAction(title: "Camera".localized, style: UIAlertActionStyle.Default){
        UIAlertAction in
        self.openCamera()
    }

    let gallaryAction = UIAlertAction(title: "Gallery".localized, style: UIAlertActionStyle.Default){
        UIAlertAction in
        self.openGallary()
    }
    let cancelAction = UIAlertAction(title: "Cancel".localized, style: UIAlertActionStyle.Cancel){
       UIAlertAction in
    }
    alertController.addAction(cameraAction)
    alertController.addAction(gallaryAction)
    alertController.addAction(cancelAction)

    self.presentViewController(alertController, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
    selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage
    collectionView.reloadData()
    dismissViewControllerAnimated(true, completion: nil)
}