2016-01-20 114 views
2

我想完成的工作:對於這個項目,我只提到兩個源文件:(1)RPPhotoLibrary.swift - 一個UICollectionViewController和(2)PhotoThumbnail.swift: - 一個UICollectionViewCell。我想從用戶的照片庫(最好是全部)加載圖像(和視頻),並將它們呈現在UICollectionViewController中每個單元的UICollectionViewCell中。出於某種原因,我能夠加載照片,但不是能夠加載所有照片。這是我的第一個源文件代碼:RPPhotoLibrary.swift:如何將照片庫加載到UICollectionView? Swift

import UIKit 
import Photos 

private let reuseIdentifier = "PhotoCell" 

class RPPhotoLibrary: UICollectionViewController,  UIImagePickerControllerDelegate { 


// By default make locating album false 
var assetCollection: PHAssetCollection! 
var photosAsset: PHFetchResult! 
var assetThumbnailSize: CGSize! 

@IBAction func cancelButton(sender: AnyObject) { 
    self.dismissViewControllerAnimated(false, completion: nil) 
} 

// =================== THIS BUTTON TAKES A PHOTO ===================================================== 
@IBAction func captureMoment(sender: AnyObject) { 
    let imagePicker = UIImagePickerController() 

    if (UIImagePickerController.isSourceTypeAvailable(.Camera)) { 

     if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil { 

      imagePicker.allowsEditing = true 
      imagePicker.sourceType = .Camera 
      imagePicker.cameraCaptureMode = .Photo 
      presentViewController(imagePicker, animated: false, completion: {}) 

     } else { 
      // postAlert("Rear camera does not exist", message: "RedPlanet cannot access the camera") 
      var alert = UIAlertView(title: "Your phone doesn't have a rear camera!", 
       message: "RedPlanet cannot access the camera.", 
       delegate: self, 
       cancelButtonTitle: "ok") 
      alert.show() 
     } 

    } else { 
     // postAlert("Camera not accessible", message: "RedPlanet cannot access the camera") 
     var alert = UIAlertView(title: "Cannot access camera.", 
      message: "RedPlanet cannot access the camera.", 
      delegate: self, 
      cancelButtonTitle: "ok") 
     alert.show() 
    } 
} 

@IBOutlet weak var thumbNail: UIImageView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let fetchOptions = PHFetchOptions() 

    let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Moment, subtype: .Any, options: fetchOptions) 

    if let first_Obj:AnyObject = collection.firstObject{ 
     //found the album 
     self.assetCollection = first_Obj as! PHAssetCollection 
    } 
} 

override func viewWillAppear(animated: Bool) { 
    // Get size of the collectionView cell for thumbnail image 
    if let layout = self.collectionView!.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.collectionView!.reloadData() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if(segue.identifier == "selectedPhoto(s)"){ 

     if let controller: SelectedPhoto = segue.destinationViewController as? SelectedPhoto{ 

      if let cell = sender as? PhotoThumbnail { 
       if let indexPath: NSIndexPath = self.collectionView!.indexPathForCell(cell){ 
        controller.index = indexPath.item 
        controller.photosAsset = self.photosAsset 
        controller.assetCollection = self.assetCollection 
       } 
      } 

     } 
    } 
} 


// MARK: UICollectionViewDataSource 

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


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

    return count; 
} 


override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell: PhotoThumbnail = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoThumbnail 

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

// MARK: - UICollectionViewDelegateFlowLayout methods 
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 
} 

// UIImagePickerControllerDelegate Methods 
func imagePickerControllerDidCancel(picker: UIImagePickerController){ 
    picker.dismissViewControllerAnimated(true, completion: nil) 
} 

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


// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item 
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { 
    return false 
} 

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

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

    self.dismissViewControllerAnimated(false, completion: nil) 

} 

}

這裏是我的第二個源文件(2)代碼:PhotoThumbnail.swift:

import UIKit 


class PhotoThumbnail: UICollectionViewCell { 

@IBOutlet weak var thumbNail: UIImageView! 

func setThumbnailImage(thumbNailImage: UIImage) { 
    self.thumbNail.image = thumbNailImage 
} 

} 

問題:出於某種原因,我無法加載全部來自8列照片庫的圖像,我想從照片庫中加載4張照片。如果任何人都可以幫我解決問題,甚至可以給我一些這樣的教程,那將不勝感激!感謝先進的哈哈。

回答

1

我假設你的問題的原因是你的代碼的這些行:

let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Moment, subtype: .Any, options: fetchOptions) 

if let first_Obj:AnyObject = collection.firstObject{ 
    //found the album 
    self.assetCollection = first_Obj as! PHAssetCollection 
} 

取結果的第一個對象是不是一張專輯,這是一個時刻(照片組)。檢查documentation

PHAssetCollectionTypeMoment。 在照片應用程序中的一刻。 「照片」應用會自動創建時間以按時間和地點對資產進行分組。

如果要在第一張專輯中顯示照片,則只需將.Moment替換爲.Album即可。如果您想顯示所有照片,則需要處理PHFetchResult中的所有對象,而不僅僅是其中的第一個。

+0

我將如何處理在PHFetchResult所有對象? – user4513956

+0

我建議不要使用集合。只需使用PHAsset.fetchAssetsWithOptions(PHFetchOptions()),您將在一個提取結果中接收所有資產。 – Tish

+0

廢話,我很困難。對不起,但你介意幫我找這樣的教程嗎? – user4513956

5

我更新了它的斯威夫特3,這是拉動中的所有照片:

import UIKit 
import Photos 


class TestViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIImagePickerControllerDelegate { 

@IBOutlet weak var cameraRollCollectionView: UICollectionView! 

var assetCollection: PHAssetCollection! 
var photosAsset: PHFetchResult<AnyObject>! 
var assetThumbnailSize: CGSize! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let fetchOptions = PHFetchOptions() 

    let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) 

    if let first_Obj:AnyObject = collection.firstObject{ 
     //found the album 
     self.assetCollection = first_Obj as! PHAssetCollection 
    } 
} 

override func viewWillAppear(_ animated: Bool) { 
    // Get size of the collectionView cell for thumbnail image 
    if let layout = self.cameraRollCollectionView!.collectionViewLayout as? UICollectionViewFlowLayout{ 
     let cellSize = layout.itemSize 

     self.assetThumbnailSize = CGSize(width: cellSize.width, height: cellSize.height) 
    } 

    //fetch the photos from collection 
    self.photosAsset = (PHAsset.fetchAssets(in: self.assetCollection, options: nil) as AnyObject!) as! PHFetchResult<AnyObject>! 


    self.cameraRollCollectionView!.reloadData() 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


// MARK: UICollectionViewDataSource 

func numberOfSections(in 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 
    } 

    return count; 
} 


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cameraCell", for: indexPath as IndexPath) as! UserImagesCollectionViewCell 

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

    PHImageManager.default().requestImage(for: asset, targetSize: self.assetThumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: {(result, info)in 
     if result != nil { 
      cell.userImage.image = result 
     } 
    }) 

    return cell 
} 

// MARK: - UICollectionViewDelegateFlowLayout methods 
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 
} 

// UIImagePickerControllerDelegate Methods 
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){ 
    picker.dismiss(animated: true, completion: nil) 
} 


} 
0

我已經這樣做了這個代碼代碼工作正常嘗試。

import UIKit 

class ViewController:    UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDe legate,UICollectionViewDelegate,UICollectionViewDataSource { 
var imagesArray :[UIImage] = [] 
@IBOutlet var collectionView: UICollectionView! 
override func viewDidLoad() { 

    super.viewDidLoad() 
    collectionView.delegate = self 
    collectionView.dataSource = self 

} 


@IBAction func getImagesAction(_ sender: Any) { 

    let picker:UIImagePickerController = UIImagePickerController() 
    picker.sourceType = .photoLibrary 
    picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)! 

    picker.delegate = self 
    picker.allowsEditing = false 
    self.present(picker, animated: true, completion: nil) 
} 

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 

    if let pickedimage = (info[UIImagePickerControllerOriginalImage] as? UIImage){ 
     imagesArray = [pickedimage] 

    } 
    collectionView.reloadData() 
    dismiss(animated: true, completion: nil) 
} 
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return imagesArray.count 
} 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell 
    //cell.imageView.image = UIImage(named: imagesArray[indexPath.row]) 
    cell.configurecell(image: imagesArray[indexPath.row]) 

    return cell 

} 

在collectionViewCell你已經採取了這種方法:

import UIKit 

    class ImageCollectionViewCell: UICollectionViewCell { 

@IBOutlet var imageView: UIImageView! 

func configurecell(image: UIImage){ 


    imageView.image = image 

    } 
} 
相關問題