Swift: Everything is loading from web in collectionViewCell except image - ios

i put a sliderCollectionViewController in UICollectionViewCell, now everything is loading from web properly without image. but i am not getting any message about error
import UIKit
import Foundation
NSObject
class Description: NSObject {
var id: Int?
var product_id: Int?
var myDescription: String?
var all_images: [String]?
var product_description: String?
}
DescriptionCollectionViewController
class DescriptionCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout{
var arrDescription = [Description]()
** Networking Request api **
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
oProduct.all_images = dt["all_images"] 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()
}
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
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
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
}()
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
}()
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
}
}
SliderCell
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)
}
}
json web

The problem is that you did:
oProduct.all_images = dt["all_images"] as? [String]
but all_images is not a string, it is a dictionary as you can see in your json.
You have to access the key image of all_images in order to show it properly.
See this:
How to access deeply nested dictionaries in Swift
You can try this:
oProduct.all_images = dt["all_images"]["image"] as? [String]

The value for key all_images is an array of dictionaries. If you want to extract all image values use the flatMap function
if let allImages = dt["all_images"] as? [[String:Any]] {
oProduct.all_images = allImages.flatMap { $0["image"] as? String }
}
But consider that the value for key image is the string representation of an URL.

Related

How can I fix the error that didSelectItemAt function for UICollectionView showing wrong item (only showing first item)?

I am trying to build an app, and there is a view which shows list of soccer leagues in collection view. I've setup Firestore database to store the require data and use the following codes to retrieve them into my app.
enum LeagueListType {
case leagueList(viewModels: [LeagueCellViewModel])
}
class LeaguesViewController: UIViewController {
private var db = Firestore.firestore()
private var leagues = [LeaguesInfo]()
private var sections = [LeagueListType]()
private var collectionView: UICollectionView = UICollectionView(
frame: .zero,
collectionViewLayout: UICollectionViewCompositionalLayout { sectionIndex, _ -> NSCollectionLayoutSection? in
return LeaguesViewController.createSectionLayout()
})
override func viewDidLoad() {
super.viewDidLoad()
title = "Leagues"
view.backgroundColor = .systemBackground
configureCollectionView()
fetchData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
private func configureCollectionView() {
view.addSubview(collectionView)
collectionView.register(UICollectionViewCell.self,
forCellWithReuseIdentifier: "cell")
collectionView.register(LeagueListCollectionViewCell.self,
forCellWithReuseIdentifier: LeagueListCollectionViewCell.identifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .systemBackground
}
private func configureModels(leagues: [LeaguesInfo]) {
self.leagues = leagues
// Configure Models
sections.append(.leagueList(viewModels: leagues.compactMap({
return LeagueCellViewModel(id: $0.id,
name: $0.name,
logo: URL(string: $0.logo))
})))
collectionView.reloadData()
}
private func fetchData() {
db.collection("leagues").addSnapshotListener { (snapshot, error) in
DispatchQueue.main.async {
guard let documents = snapshot?.documents else {
print("No league data")
return
}
self.leagues = documents.compactMap { (documentSnapshot) -> LeaguesInfo in
let data = documentSnapshot.data()
let id = data["id"] as? String ?? ""
let name = data["name"] as? String ?? ""
let logo = data["logo"] as? String ?? ""
let leaguess = LeaguesInfo(id: id, name: name, logo: logo)
self.configureModels(leagues: [leaguess])
self.collectionView.reloadData()
return leaguess
}
}
}
}
}
Here is cellForItemAt part.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let type = sections[indexPath.section]
switch type {
case .leagueList(let viewModels):
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LeagueListCollectionViewCell.identifier,
for: indexPath) as? LeagueListCollectionViewCell else {
return UICollectionViewCell()
}
let viewModel = viewModels[indexPath.row]
cell.configure(with: viewModel)
return cell
}
}
And I use the following codes for didSelectItemAt function in extension.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let league = leagues[indexPath.row]
let vc = LeagueViewController(league: league)
vc.title = league.name
vc.navigationItem.largeTitleDisplayMode = .never
navigationController?.pushViewController(vc, animated: true)
}
The problem is that didSelectItemAt always returning wrong item. It's only showing viewcontroller for the first item of the leagues no matter which item I select.
Could you please enlighten me how to fix it?

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()
}
}

How can I execute the collectionView methods of a class from another one?

I have my class CardSensors which is has a collectionView which is filled with another XIB
class CardSensors: UIView {
#IBOutlet weak var botName: UILabel!
#IBOutlet weak var sensorsCollectionView: UICollectionView!
var sensors = [[String: Any]]()
var viewModel: NewsFeedViewModel! {
didSet {
setUpView()
}
}
func setSensors(sensors: [[String: Any]]){
self.sensors = sensors
}
static func loadFromNib() -> CardSensors {
return Bundle.main.loadNibNamed("CardSensor", owner: nil, options: nil)?.first as! CardSensors
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupCollectionView(){
let nibName = UINib(nibName: "SensorCollectionViewCell", bundle: Bundle.main)
sensorsCollectionView.register(nibName, forCellWithReuseIdentifier: "SensorCollectionViewCell")
}
func setUpView() {
botName.text = viewModel.botName
}
}
extension CardSensors: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SensorCollectionViewCell", for: indexPath) as? SensorCell else {
return UICollectionViewCell()
}
cell.dateLabel.text = sensors[indexPath.row]["created_at"] as? String
cell.sensorType.text = sensors[indexPath.row]["type"] as? String
cell.sensorValue.text = sensors[indexPath.row]["value"] as? String
cell.sensorImage.image = UIImage(named: (sensors[indexPath.row]["type"] as? String)!)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sensors.count
}
}
Im creating an object in another class like this but I want this to call the methods of the collectionView for it to load the info.
let sensorView = CardSensors.loadFromNib()
sensorView.sensors = sensores
sensorView.setupCollectionView()
The problem is that the collectionView methods are never being called. What can I do to call them from my other class?
You need to set the data souce
sensorsCollectionView.register(nibName, forCellWithReuseIdentifier: "SensorCollectionViewCell")
sensorsCollectionView.dataSource = self
sensorsCollectionView.reloadData()
Then inside your vc , make it an instance variable
var sensorView:CardSensors!
sensorView = CardSensors.loadFromNib()
sensorView.sensors = sensores
sensorView.setupCollectionView()

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

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