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! 

} 

的圖像 - 創建陣列,在的CollectionView

顯示
+0

你能解決問題到現在? –

+0

@SunilPrajapati是的,但需要這樣的電池代碼 –

回答

1

請編輯方法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) 
} 
+0

如果不行或您需要其他幫助,請在此處註釋 –

+0

顯示彈出式縮放圖像。當我點擊其他單元格 –

+0

時,請刪除didSelect方法代碼並檢查 –

1

基本上你必須創建一個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) 

} 
+0

如何在此陣列中添加圖像,以及如何在單元格按鈕中顯示此圖像。 –

+0

你的數據源是字符串類型和單元格沒有imageview ..你想如何顯示圖像? – 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. 
}} 

型號

class Images{ 
    var image:UIImage? 
} 
+0

謝謝,那添加新單元格,但我怎麼從圖像選擇器 –

+0

創建一個模型來存儲從uIImagePicker視圖委託方法didFinishPickingMediaWithInfo收到的圖像,並使用該模型的數組而不是items數組。希望你得到我想說的話? –

+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

您的單元格沒有排序填充圖像,所以我會建議使用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) 
相關問題