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

时间:2016-12-27 06:27:29

标签: swift uicollectionview uiimagepickercontroller uicollectionviewcell

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

CollectionView类

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

5 个答案:

答案 0 :(得分:1)

基本上你必须创建一个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)

}

答案 1 :(得分:1)

// 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?
}

答案 2 :(得分:1)

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

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

// MARK: - UICollectionViewDataSource protocol

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

在集合视图的数据源方法中返回 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)
 }

最后,插入新单元格而不是重新加载整个集合视图会更便宜。

答案 3 :(得分:1)

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

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)
}

答案 4 :(得分:0)

你的单元格没有被命令填充图像,所以我建议使用Dictionary数据结构而不是Array。在更改时将图像更新为项目字典以获取索引路径,然后重新加载数据。

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

}

在图像选择器回调中更新dictonary。

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