2016-07-12 11 views
2

현재 collectionview이 있습니다. library에서 이미지를로드하는 셀이 있습니다. 버튼을 사용하여 셀을 추가하기 전에 camera을 엽니 다. 어떻게 할 수 있습니까 ??collectionview 셀에 버튼을 추가하는 방법

import UIKit 
import Photos 
import MobileCoreServices 
private let reuseIdentifier = "PhotoCell" 
class AddPhotoViewController: UIViewController , UIImagePickerControllerDelegate ,UINavigationControllerDelegate ,UICollectionViewDataSource ,UICollectionViewDelegate{ 

    @IBOutlet weak var photoAlbum: UICollectionView! 

    var TakenImage : UIImageView! 
    var selectedImage : UIImage! 
    var pickedImage : UIImage! 
    var assetCollection: PHAssetCollection! 
    var photosAsset: PHFetchResult! 
    var assetThumbnailSize: CGSize! 
    let imagePicker: UIImagePickerController! = UIImagePickerController() 
    var cameraon : Bool = false 
    var index : [NSIndexPath]! 

    var note : String! 
    var noteAlreadyEntered = false 
    override func viewDidLoad() 
    { 
     super.viewDidLoad() 

     let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: nil) 

     var i = 0 
     repeat 
     { 
      if let first_Obj:AnyObject = collection.objectAtIndex(i) 
      { 
       self.assetCollection = first_Obj as! PHAssetCollection 
      } 
      i++ 
     }while(i < collection.count) 



     // Do any additional setup after loading the view. 
    } 

    @IBAction func takePhoto(sender: AnyObject) { 

     let picker = UIImagePickerController() 
     picker.delegate = self 
     picker.sourceType = .Camera 
     presentViewController(picker, animated: true,completion : nil) 
     save(TakenImage.image!) 


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

     TakenImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage ; dismissViewControllerAnimated(true, completion: nil) 

    } 
    @IBAction func save(sender: AnyObject) 
    { 
     UIImageWriteToSavedPhotosAlbum(TakenImage.image!, self, "image:didFinishSavingWithError:contextInfo:", nil) 
    } 
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) 
    { 
     if error == nil { 
      let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert) 
      ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      presentViewController(ac, animated: true, completion: nil) 
     } else 
     { 
      let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert) 
      ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      presentViewController(ac, animated: true, completion: nil) 
     } 
    } 


     override func viewWillAppear(animated: Bool) 
    { 
     if let layout = self.photoAlbum!.collectionViewLayout as? UICollectionViewFlowLayout{ 
      let cellSize = layout.itemSize 

      self.assetThumbnailSize = CGSizeMake(cellSize.width, cellSize.height) 
     } 

     //fetch the photos from collection 
     self.photosAsset = PHAsset.fetchAssetsInAssetCollection(self.assetCollection, options: nil) 

     self.photoAlbum!.reloadData() 


    } 

    // MARK: UICollectionViewDelegate 

    /* 
    // Uncomment this method to specify if the specified item should be selected 
    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { 
    return true 
    } 
    */ 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
    { 
     if (segue.identifier == "savePhoto") 
     { 
      if let controller : NoteDetailViewController = segue.destinationViewController as? NoteDetailViewController 
      { 
       controller.takinPhoto = true 
      // controller.imageView2.image = TakenImage.image 
       if(noteAlreadyEntered == true) 
       { 
        controller.content = note 
        controller.imageView.image = TakenImage.image 
       } 
       else 
       { 
        controller.imageView2.image = TakenImage.image 
       } 

      } 
     } 
      if (segue.identifier == "saveSelected") 
     { 


      let cell = sender as! PhotoAlbumCollectionViewCell 
      let indexPath = photoAlbum.indexPathForCell(cell) 
      let destVC = segue.destinationViewController as! NoteDetailViewController 
      destVC.asset = self.photosAsset[indexPath!.item] as! PHAsset 

      destVC.flag = true 
      if(noteAlreadyEntered == true) 
      { 
       destVC.content = note 
      } 

     } 



    } 

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
    { 
    } 



    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int 
    { 
     // #warning Incomplete implementation, return the number of sections 
     return 1 
    } 

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    { 
     // #warning Incomplete implementation, return the number of items 
     var count: Int = 0 

     if(self.photosAsset != nil){ 
      count = self.photosAsset.count 
     } 
     print("\(self.photosAsset.count)") 
     return count + 1 
    } 
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
    { 
     let cell: PhotoAlbumCollectionViewCell = photoAlbum.dequeueReusableCellWithReuseIdentifier("PhotoCell", forIndexPath: indexPath) as! PhotoAlbumCollectionViewCell 

     //Modify the cell 
     let asset: PHAsset = self.photosAsset[indexPath.item] as! PHAsset 

     PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: self.assetThumbnailSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info)in 
      if let image = result { 
       cell.setThumbnailImage(image) 
      } 
     }) 

     return cell 
    } 



    func collectionView(collectinView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { 
     return 4 
    } 

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { 
     return 1 
    } 

    func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { 
     return false 
    } 

    func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { 
     return false 
    } 

    func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { 

     self.dismissViewControllerAnimated(false, completion: nil) 

    } 

} 
+0

는 완전히 세포의 크기를 획득 콜렉션 뷰의 셀에 이미지 뷰의 경우 예 당신은 콜렉션 뷰의 대리자 메서드를 사용하지 않는 이유 - 같은 일을 할 것입니다 버튼을 추가하지 않고 didSelectRowAtIndexPath를, . –

답변

0

사용자 지정 클래스를 사용하고 있다고 가정합니다. collectionview 셀의 경우 이미 이미지 앞에 카메라를 열 수있는 옵션을 추가하기 위해 카메라 이미지를 배열의 첫 번째 인덱스에 추가했습니다. 이것은 이것을하는 쉬운 방법입니다.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Identifier", forIndexPath: indexPath) as! YourCustomcell 

cell.imageView.image = UIImage(named: arryImage[indexPath.item] as String) 

return cell 
} 
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){ 
    if indexPath.item == 0 { 
     //Code to open camera 
    }else{ 

    }   
} 

이것은 원하는 것을 얻는 가장 간단한 방법입니다. 당신은 단지 numberOfItemsInSection 방법에 1 배열 수를 증가시키고

if indexPath.item == 0 { 
      cell.imageView.image = UIImage(named: "CameraImage") 
}else{ 
      cell.imageView.image = UIImage(named: arryImage[(indexPath.item)-1] as String) 
} 

didSelectItemAtIndexPath 방법은 동일하게 유지됩니다 cellForItemAtIndexPath 방법에서 다음과 같이 변경합니다, 이미지의 배열에 카메라 이미지를 추가 할 해달라고합니다. 끝에서 opencamera 함수를 원한다면 적절하게 변경하십시오.

희망이 당신을 도울 것입니다 :)

1

numberOfItemInSection 방법에서 이미 한 번 더 카운트하고 있습니다. 그러니 그냥 변경하려면 같은 cellForItemAtIndexPath

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell: PhotoAlbumCollectionViewCell = photoAlbum.dequeueReusableCellWithReuseIdentifier("PhotoCell", forIndexPath: indexPath) as! PhotoAlbumCollectionViewCell 
    if (indexPath.item == 0) { 
     let btn = UIButton(frame: cell.contentView.bounds) //Set your frame that you want 
     btn.setBackgroundImage(UIImage(named: "add"), forState: .Normal) 
     btn.addTarget(self, action: #Selector(addNewImage(_:)), forControlEvents: .TouchUpInside) 
     cell.contentView.addSubview(btn) 
    } 
    else { 
     //Modify the cell 
     let asset: PHAsset = self.photosAsset[indexPath.item-1] as! PHAsset 
     PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: self.assetThumbnailSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info)in 
      if let image = result { 
       cell.setThumbnailImage(image) 
      } 
     }) 
    } 
    return cell 
} 

지금 당신은 당신의 ViewController

override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { 
    if (identifier == "saveSelected") 
    { 
     let cell = sender as! PhotoAlbumCollectionViewCell 
     let indexPath = tableView.indexPathForCell(cell) 
     if (indexPath.row == 0) { 
      self.addNewImage(UIButton()) // To Open Camera 
      return false //To stop perform Segue. 
     } 
    } 
    return true 
} 
shouldPerformSegueWithIdentifier 메소드를 오버라이드 (override) 할 필요가 당신의 segue 문제를 해결하기 위해이

func addNewImage(sender: UIButton) { 
    //Add the code of ImagePicker 
} 

처럼 ViewControlleraddNewImage 방법을 추가

+0

내 collectionview 셀에 이미지 뷰를 추가했습니다. 그게 문제가 될 수 있습니까? –

+0

아니요. 문제 없습니다. –

+0

업데이트 된 코드로 질문을 업데이트 할 수 있습니까? –

관련 문제