如何在单元格末尾添加CollectionView自定义单元格?
我有一组图像,显示在集合视图中,我创建了一个单元格,当我点击最后一个打开图像选择器的单元格时。 - >可以在此单元格中设置所选图像,并自动为此添加新单元格。 (我不知道这样的想法,请帮忙,谢谢)如何在单元格末尾添加CollectionView自定义单元格?
的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
显示
请编辑方法ONLY,并添加一些方法:
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)
}
如果不行或您需要其他帮助,请在此处注释 –
显示弹出式缩放图像。当我点击其他单元格 –
时,请删除didSelect方法代码并检查 –
基本上你必须创建一个item
类型的对象,因为它是collectionview的数据源,最后在item
数组中添加该对象,并重新加载collectionview。
可能您需要在func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
方法中执行此操作。
编辑:
var items = [UIImage]()
//可能有一些图像对象从UIImagePickerView代表接收图像
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)
}
如何在此阵列中添加图像,以及如何在单元格按钮中显示此图像。 –
你的数据源是字符串类型和单元格没有imageview ..你想如何显示图像? – preetam
我需要在按钮背景图像,cell.btnSelectImage.setBackgroundImage(choosenImage,forState:.Normal)从图像选择器 –
// 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.
}}
型号
class Images{
var image:UIImage?
}
谢谢,那添加新单元格,但我怎么从图像选择器 –
创建一个模型来存储从uIImagePicker视图委托方法didFinishPickingMediaWithInfo收到的图像,并使用该模型的数组而不是items数组。希望你得到我想说的话? –
是的,我明白你说什么,但我不知道如何创建模态数组。 –
我的做法将是对有一个var say itemsCount用1初始化而不是你的var items这是一个数组。也有一个图像数组。
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单元可能会或可能不会有图像。此外,基于单元格的图像可能会有所不同。要设置您可以使用
cell.btnSelectImage.setTitle(String(self.itemsCount), forState: .Normal)
if images.indices.contains(indexPath.row) {
cell.btnSelectImage.setBackgroundImage(self.images[indexPath.row], forState: .Normal)
}
最后这将是更便宜的插入,而不是重新加载整个集合视图的新小区称号。
cell.btnSelectImage.setBackgroundImage(choosenImage,forState :.Normal)不能工作,图像不能在单元格中显示,我如何设置背景图像 –
请问你能解释一下,我把这个代码放在哪里? –
我刚刚编辑了我的答案。核实。为什么它没有显示,我已经在cellForRowAtIndexPath的最后一段中解释过了。 –
您的单元格没有排序填充图像,所以我会建议使用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)
你能解决问题到现在? –
@SunilPrajapati是的,但需要这样的电池代码 –