Accessing images in DocumentDirectory iOS and UICollectionView - ios

In my app, the user selects an image from camera roll, and it is saved in a document directory. The image is then displayed on the ViewController where they selected the image. I want the image to be appended to a UICollectionView. How can I access the image/append the image from the documentDirectory? Please see my code below. Let me know if you need other pieces of my project.
DetailViewController(Where I initially display the photo):
class DetailViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
...
var imageStore: ImageStore!
#IBAction func takePicture(sender: UIBarButtonItem) {
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
imagePicker.sourceType = .Camera
} else {
imagePicker.sourceType = .PhotoLibrary
}
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageStore.setImage(image, forKey: item.itemKey)
imageView.image = image
dismissViewControllerAnimated(true, completion: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let key = item.itemKey
if let imageToDisplay = imageStore.imageForKey(key) {
imageView.image = imageToDisplay
}
}
ImageStore(How I initially store the photo):
import UIKit
class ImageStore: NSObject {
let cache = NSCache()
func setImage(image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key)
let imageURL = imageURLForKey(key)
if let data = UIImageJPEGRepresentation(image, 0.5) {
data.writeToURL(imageURL, atomically: true)
}
}
func imageForKey(key: String) -> UIImage? {
if let existingImage = cache.objectForKey(key) as? UIImage {
return existingImage
}
let imageURL = imageURLForKey(key)
guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
return nil
}
cache.setObject(imageFromDisk, forKey: key)
return imageFromDisk
}
func deleteImageForKey(key: String) {
cache.removeObjectForKey(key)
let imageURL = imageURLForKey(key)
do {
try NSFileManager.defaultManager().removeItemAtURL(imageURL)
}
catch let deleteError {
print("Error removing the image from disk: \(deleteError)")
}
}
func imageURLForKey(key: String) -> NSURL {
let documentsDirectories =
NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.URLByAppendingPathComponent(key)
}
}
UICollectionView:
import UIKit
class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 300, height: 490)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView!.registerClass(FoodCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
var images: [UIImage] = [
]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! FoodCell
cell.textLabel.text = ""
cell.imageView.image = images[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
print("User tapped on item \(indexPath.row)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

You can try to save and get your image by this way:
//Save image
let img = UIImage() // Image from your picker
let data = UIImagePNGRepresentation(img)!
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
try data.writeToFile("\(documentsPath)myImage", options: [])
} catch {
print("Error")
}
// Get image
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let readData = try NSData(contentsOfFile: "\(documentsPath)myImage", options: [])
let retreivedImage = UIImage(data: readData)
}
catch {
print("Error")
}
Same way as https://stackoverflow.com/a/35685943/2894160

Related

ios(Swift) collectionView don't show up

I'd like to show the CollectionView inside the B ViewController using the A ViewController's button. Image.
The information in the image is in the json file.
Gets the information and invokes the image in the Asset file.
There's no problem getting the data in json.
But nothing appears. Using the buttons in the A ViewController,
What's the problem?
The bottom is my code.
Thank you.
A ViewController
//MARK: 4. #objc Button Action
#objc func topHand(){
let cham = ChampViewViewController()
cham.modalPresentationStyle = .fullScreen
present(cham, animated: true, completion: nil)
}
B ViewController
class ChampViewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var nameArrayCount = 0
var nameArray = [String]()
private var collectionView : UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
let indenti = "top"
let layout = UICollectionViewLayout()
getJson(line: indenti)
collectionView = UICollectionView(frame: .zero,collectionViewLayout: layout)
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.register(ChamCellCollectionViewCell.self, forCellWithReuseIdentifier: ChamCellCollectionViewCell.identifier)
guard let collectionsView = collectionView else { return }
view.addSubview(collectionsView)
collectionsView.frame = view.bounds
}
private func getJson(line:String){
let cellUrl = Bundle.main.url(forResource: line, withExtension: "json")
let cellData = NSData(contentsOf: cellUrl!)
do {
let modelJson = try JSONSerialization.jsonObject(with: cellData! as Data, options: .allowFragments ) as! NSArray
var models : [Model] = []
modelJson.forEach { json in
guard let dic = json as? [String : AnyObject] else {
return
}
let newModel = Model(name: dic["이름"] as! String,
line: dic["주라인"] as! String, type:
dic["성향"] as! String,
hp: dic["체력"] as! Int,
hpRe: dic["추가체력"] as! Int,
attackPower: dic["공격력"] as! Double,
attackPowerRe: dic["추가공격력"] as! Double,
attackSpeed: dic["공속"] as! Double,
attackSpeedRe: dic["추가공속"] as! Double,
defensive: dic["방어력"] as! Double,
defensiveRe: dic["추가방어력"] as! Double,
magicDefensive: dic["마저"] as! Double,
magicDefensiveRe: dic["추가마저"] as! Double,
row: dic["row"] as! Int,
column: dic["column"] as! Int)
models.append(newModel)
}
for data in models {
let key = data.name
nameArray.append(key)
}
nameArrayCount = nameArray.count
}catch {
fatalError()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return nameArrayCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ChamCellCollectionViewCell.identifier, for: indexPath) as? ChamCellCollectionViewCell else {
fatalError()
}
cell.imageConfigure(with: UIImage(named:"가렌"))
return cell
}
}
B ViewController CollectionViewCell Class
import UIKit
class ChamCellCollectionViewCell : UICollectionViewCell{
static let identifier = "ChamCellCollectionViewCell"
private let imageView : UIImageView = {
let image = UIImageView()
image.contentMode = .scaleAspectFit
return image
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func imageConfigure(with image : UIImage?) {
imageView.image = image
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = contentView.bounds
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
}
Add this code to getJson() before the catch block:
DispatchQueue.main.async { [weak self] in
self?.collectionView?.reloadData()
}
Try with a didSet for your nameArrayCount.
var nameArrayCount = 0{
didSet{
collectionView.reloadData()
}
}

Why isn't my Image displaying in the UIImageView?

I want to get an if statement which, if the selected button corresponded to the first image view, set it to the first image, else set it to the second image view... But, once I select the image from the image picker, it just ignores it and moves on like if nothing happened.
Here is my code:
(it down under the image picker controller func...)
class UploadSubPostCell: UICollectionViewCell {
#IBOutlet weak var previewStep: UIImageView!
}
class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var previewImage: UIImageView!
#IBOutlet weak var postBtn: UIButton!
#IBOutlet weak var selectBtn: UIButton!
#IBOutlet weak var postscollectionview: UICollectionView!
#IBOutlet weak var selectStepsBtn: UIButton!
var picker = UIImagePickerController()
var isThumbnailImage = true
var subpostsArray = [UIImage]()
var subposts = [SubPost]()
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBarItems()
picker.delegate = self
}
func setupNavigationBarItems() {
navigationItem.title = "Upload"
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
let path = IndexPath(item: 0, section: 0)
let cell = self.postscollectionview.cellForItem(at: path) as? UploadSubPostCell
if isThumbnailImage{
previewImage.image = image
} else {
cell?.previewStep.image = image
}
selectBtn.isHidden = false
selectStepsBtn.isHidden = false
postBtn.isHidden = false
if isThumbnailImage == false {
subpostsArray.append(image)
subposts.count + 1
print("Appended image to array:", subpostsArray)
}
}
picker.dismiss(animated: true, completion: nil)
}
#IBAction func selectStepPressed(_ sender: Any) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
isThumbnailImage = false
self.present(picker, animated: true, completion: nil)
}
#IBAction func selectPressed(_ sender: Any) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
isThumbnailImage = true
self.present(picker, animated: true, completion: nil)
}
#IBAction func addNewPressed(_ sender: Any) {
}
#IBAction func postPressed(_ sender: Any) {
AppDelegate.instance().showActivityIndicator()
let uid = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let storage = Storage.storage().reference(forURL: "gs://mobile-d9fcd.appspot.com")
let key = ref.child("posts").childByAutoId().key
let imageRef = storage.child("posts").child(uid).child("\(key).jpg")
let data = UIImageJPEGRepresentation(self.previewImage.image!, 0.6)
let uploadTask = imageRef.putData(data!, metadata: nil) { (metadata, error) in
if error != nil {
print(error!.localizedDescription)
AppDelegate.instance().dismissActivityIndicator()
return
}
imageRef.downloadURL(completion: { (url, error) in
if let url = url {
let feed = ["userID" : uid,
"pathToImage" : url.absoluteString,
"likes" : 0,
"author" : Auth.auth().currentUser!.displayName!,
"postID" : key] as [String : Any]
let postFeed = ["\(key)" : feed]
ref.child("posts").updateChildValues(postFeed)
AppDelegate.instance().dismissActivityIndicator()
self.picker.dismiss(animated: true, completion: nil)
}
})
}
uploadTask.resume()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
cell.postImage.downloadImage(from: self.posts[indexPath.row].pathToImage)
cell.authorLabel.text = self.posts[indexPath.row].author
cell.likeLabel.text = "\(self.posts[indexPath.row].likes!) Likes"
cell.postID = self.posts[indexPath.row].postID
}
}
}
In didFinishPickingMediaWithInfo, you should save the image with the dataSource, if you know what cell the image goes into, use tableView.reloadRows(at indexPaths:) to reload the cell. Add the image to cell.previewStep.image in cellForRowAt()
if you are using swift version 4.2 and above, you should be replacing:
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
by:
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {

ios: All data is loading from json web request except SliderCollectionViewCell

I have sliderCollectionViewController in UICollectionViewCell, try to loading data from json web, all data is loading without image. Here I like to load images in slideCollectionViewCell which created in a collectionViewCell.
import UIKit
import Foundation
**DescriptionObject**
`class Description: NSObject {
var id: Int?
var product_id: Int?
var myDescription: String?
var product_description: String?
var all_images: [String]?
}
**DescriptionCollectionViewController with slideCollectionViewController**
class DescriptionCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout{
var arrDescription = [Description]()
**json request**
func loadDescription(){
ActivityIndicator.customActivityIndicatory(self.view, startAnimate: true)
let url = URL(string: ".........")
URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in
if error != nil {
print(error ?? 0)
}
else {
do {
let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any]
let myProducts = json["products"] as? [String: Any]
let myData = myProducts?["data"] as? [[String:Any]]
myData?.forEach { dt in
let oProduct = Description()
oProduct.id = dt["id"] as? Int
oProduct.product_id = dt["product_id"] as? Int
oProduct.myDescription = dt["description"] as? String
oProduct.product_description = dt["product_description"] as? String
if let allImages = dt["all_images"] as? [[String:Any]] {
oProduct.all_images = allImages.flatMap { $0["image"] as? String }
}
self.arrDescription.append(oProduct)
}
} catch let error as NSError {
print(error)
}
}
DispatchQueue.main.async(execute: {
ActivityIndicator.customActivityIndicatory(self.view, startAnimate: false)
self.collectionView?.reloadData()
})
}.resume()
}
fileprivate let cellId = "cellId"
fileprivate let descriptionCellId = "descriptionCellId"
override func viewDidLoad() {
super.viewDidLoad()
self.loadDescription()
collectionView?.register(DescriptionCell.self, forCellWithReuseIdentifier: descriptionCellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrDescription.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: descriptionCellId, for: indexPath) as! DescriptionCell
cell.descriptionOb = arrDescription[indexPath.item]
return cell
}
**DescriptionCollectionViewCell**
class DescriptionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var descriptionOb: Description!{
didSet{
descriptionTextView.text = descriptionOb?.myDescription
couponTextView.text = descriptionOb?.product_description
slideCollectionView.reloadData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let descriptionTextView: UITextView = {
let textview = UITextView()
textview.text = "Description is the pattern of development "
return textview
}()
let couponTextView: UITextView = {
let textview = UITextView()
textview.text = "Description is the pattern of development "
return textview
}()
fileprivate let cellId = "cellId"
lazy var slideCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.clear
return cv
}()
func setupCell() {
slideCollectionView.dataSource = self
slideCollectionView.delegate = self
slideCollectionView.isPagingEnabled = true
slideCollectionView.register(SlideCell.self, forCellWithReuseIdentifier: cellId)
addSubview(slideCollectionView)
addSubview(descriptionTextView)
addSubview(couponTextView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = descriptionOb?.all_images?.count{
return count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SlideCell
if let imageName = descriptionOb?.all_images?[indexPath.item] {
cell.imageView.image = UIImage(named: imageName)
}
return cell
}
}
**SlideCollectionViewCell**
class SlideCell: UICollectionViewCell{
override init(frame: CGRect) {
super.init(frame: frame)
setupCellSlider()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let imageView: CustomImageView = {
let iv = CustomImageView()
iv.contentMode = .scaleAspectFill
iv.image = UIImage(named: "defaultImage3")
iv.backgroundColor = UIColor.green
return iv
}()
func setupCellSlider() {
backgroundColor = .green
addSubview(imageView)
}
}`
**Image Extension**
let imageCache = NSCache<AnyObject, AnyObject>()
class CustomImageView: UIImageView {
var imageUrlString: String?
func loadImageUsingUrlString(_ urlString: String) {
imageUrlString = urlString
guard let urlEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
print("Encoding not done")
return
}
let url = URL(string: urlEncoded)
image = nil
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
if let url = url {
URLSession.shared.dataTask(with: url, completionHandler: {(myData, respones, error) in
if error != nil {
print(error ?? 0)
return
}
if let myData = myData {
DispatchQueue.main.async(execute: {
let imageToCache = UIImage(data: myData)
if self.imageUrlString == urlString {
self.image = imageToCache
}
if let imageToCache = imageToCache {
imageCache.setObject(imageToCache, forKey: urlString as AnyObject)
}
})
}
}).resume()
}
}
}
json web data
You should use the method in UIImageView subclass CustomImageView
so instead of
cell.imageView.image = UIImage(named: imageName)
try this:
cell.imageView.loadImageUsingUrlString(imageName)
in you cellForItem method of DescriptionCell

Building SQLite Database with Photos

I am aiming to display images collected by the user from a DetailViewController, in a UICollectionView controller. I want to use a SQLite Database, but am unsure how to start it, seeing as I already have most of my app built and established. Below see my DetailViewController (where the images are collection and displayed), ImageStore.swift (Where the images are currently being stored), and the UICollectionView controller.
ImageStore.swift:
class ImageStore: NSObject {
let cache = NSCache()
func setImage(image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key)
let imageURL = imageURLForKey(key)
if let data = UIImageJPEGRepresentation(image, 0.5) {
data.writeToURL(imageURL, atomically: true)
}
}
func imageForKey(key: String) -> UIImage? {
if let existingImage = cache.objectForKey(key) as? UIImage {
return existingImage
}
let imageURL = imageURLForKey(key)
guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
return nil
}
cache.setObject(imageFromDisk, forKey: key)
return imageFromDisk
}
func deleteImageForKey(key: String) {
cache.removeObjectForKey(key)
let imageURL = imageURLForKey(key)
do {
try NSFileManager.defaultManager().removeItemAtURL(imageURL)
}
catch let deleteError {
print("Error removing the image from disk: \(deleteError)")
}
}
func imageURLForKey(key: String) -> NSURL {
let documentsDirectories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.URLByAppendingPathComponent(key)
}
DetailViewController:
var imageStore: ImageStore!
#IBAction func takePicture(sender: UIBarButtonItem) {
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
imagePicker.sourceType = .Camera
} else {
imagePicker.sourceType = .PhotoLibrary
}
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageStore.setImage(image, forKey: item.itemKey)
imageView.image = image
dismissViewControllerAnimated(true, completion: nil)
}
UICollectionView:
class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 100, height: 100)
let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
myCollectionView.dataSource = self
myCollectionView.delegate = self
myCollectionView.registerClass(RDCellCollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
myCollectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(myCollectionView)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
var images: [UIImage] = [
]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! RDCellCollectionViewCell
myCell.imageView.image = images[indexPath.item]
return myCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
print("User tapped on item \(indexPath.row)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

Creating UICollectionView programmatically

I am learning how to create a UICollectionView programmatically. I want to create a grid of pictures collected from the user in another part of the app.
Will this sample code help me accomplish this? Also, how do I configure the data to emit the image I want? My source code is below.
UICollectionView:
class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
let imageStore = ImageStore()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 100, height: 100)
let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
myCollectionView.dataSource = self
myCollectionView.delegate = self
myCollectionView.registerClass(RDCellCollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
myCollectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(myCollectionView)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
var images: [UIImage] = [
]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! RDCellCollectionViewCell
myCell.imageView.image = images[indexPath.item]
myCell.backgroundColor = UIColor.grayColor()
return myCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
print("User tapped on item \(indexPath.row)")
}
}
ImageStore.swift:
class ImageStore: NSObject {
let cache = NSCache()
func setImage(image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key)
let imageURL = imageURLForKey(key)
if let data = UIImageJPEGRepresentation(image, 0.5) {
data.writeToURL(imageURL, atomically: true)
}
}
func imageForKey(key: String) -> UIImage? {
if let existingImage = cache.objectForKey(key) as? UIImage {
return existingImage
}
let imageURL = imageURLForKey(key)
guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
return nil
}
cache.setObject(imageFromDisk, forKey: key)
return imageFromDisk
}
func deleteImageForKey(key: String) {
cache.removeObjectForKey(key)
let imageURL = imageURLForKey(key)
do {
try NSFileManager.defaultManager().removeItemAtURL(imageURL)
}
catch let deleteError {
print("Error removing the image from disk: \(deleteError)")
}
}
func imageURLForKey(key: String) -> NSURL {
let documentsDirectories =
NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.URLByAppendingPathComponent(key)
}
}
You're on the right track. You'll need to create a subclass of UICollectionViewCell that contains a UIImageView; this will let you plug the correct UIImage into it in cellForItemAtIndexPath.
This describes how to hook up your custom cell:
Create UICollectionViewCell programmatically without nib or storyboard
As for getting the correct image, you'll need to map the index path to your image store somehow, so that an item number corresponds to the correct image key.
If the task is to add an image, you should use something like this in cellForItemAtIndexPath:
let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath)
myCell.backgroundColor = UIColor.blueColor()
let imageView = UIImageView(frame: cell.contentView.frame)
cell.contentView.addSubview(imageView)
imageView.image = //Here you should get right UIImage like ImageStore().imageForKey("YOUR_KEY")
return myCell
Or you can use custom UICollectionViewCell subclass as Joshua Kaden wrote.

Resources