3

У меня есть массив изображений, которые отображаются в виде коллекции, я создаю ячейку для, когда я нажимаю на последнюю ячейку, открывающую подборщик изображений. -> выбранное изображение можно установить в этой ячейке и автоматически добавить новую ячейку последним. (я понятия не имею об этом, пожалуйста, помогите, спасибо)Как добавить пользовательскую ячейку 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! 

} 

-create массив для изображений, показывая в CollectionView

+0

вы фиксированной вашу проблему до сих пор? –

+0

@SunilPrajapati ДА, но для этого нужен код для тестирования –

ответ

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

, а если нет, или вам нужна какая-то другая помощь, тогда прокомментируйте здесь –

+0

Показаны всплывающие окна с увеличенным изображением. Когда я нажимаю на другую ячейку –

+0

, удалите код метода didSelect и проверьте –

1

В основном вы должны создайте объект типа item, потому что это ваш источник данных для коллекции, добавьте его в массив item и просто перезагрузите viewview.

Возможно, вам нужно сделать это в методе func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]).

Edit:

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) 

} 
+0

Как добавить изображение в этот массив и как отображать эти изображения в кнопке соты.? –

+0

ваш источник данных имеет тип строки, а ячейка не имеет изображения. Как вы хотите отображать изображение? – preetam

+0

Мне нужно изображение в фоновом режиме кнопки, cell.btnSelectImage.setBackgroundImage (choosenImage, forState: .Normal) из подборщика изображений –

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? 
} 
+0

Спасибо, что добавьте новую ячейку, но как я добавьте выбранные изображения в новую созданную ячейку, с помощью подборщика изображений –

+0

создайте модель для хранения изображения, полученного из метода делегирования представления uIImagePicker, didFinishPickingMediaWithInfo и используйте массив этой модели вместо массива элементов. надеюсь, что у меня будет то, что я пытаюсь сказать? –

+0

Да, я понимаю, что вы говорите, но я не знаю, как создать модальный массив. –

1

Мой подход будет в имеют 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) 
} 

Наконец, это будет дешевле, чтобы вставить новую ячейку вместо перезагрузки всей представление коллекции.

+0

cell.btnSelectImage.setBackgroundImage (choosenImage, forState : .Normal) не может работать, изображение не отображается в ячейке, как я устанавливаю фоновое изображение. –

+0

Можете ли вы объяснить, пожалуйста, где я помещаю этот код? –

+0

Я только что отредактировал свой ответ. Проверь это. Почему он не отображается, я уже объяснил в последнем параграфе для cellForRowAtIndexPath. –

0

Ваша ячейка не заказана, заполненная изображениями, поэтому я предлагаю использовать структуру данных словаря вместо 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 

} 

Update справочник на захватывающего изображение обратного вызова.

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