Creating UICollectionView programmatically - ios

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.

Related

CollectionCell displays wrong image?

I have a TableView with cells, and one cell is holding a CollectionView.
Inside the CollectionView, I have cells with UIImageViews.
If I add new elements to the datasource while the CollectionView is visible then it works fine.
But if I scroll down in the TableView, add the new elements then scroll up, then even though it adds the new cells, they are displaying the wrong image.
Video: https://youtu.be/QwvMv2xaaAI
Code:
MainViewController(Not the whole)
func addNewPhotos(newPhotosArray: [Photo]){
var collectionViewInserts : [IndexPath] = []
for (i in 0...newPhotosArray.count) {
// I add the new photos to the datasource
PhotosStore.shared.photos.insert(newPhotosArray[i], at: 0)
// Then save the indexPath what needs to be inserted
collectionViewInserts.insert(IndexPath(row: i, section: 0), at: 0)
}
if let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? PhotosCell {
cell.photosCollectionView.performBatchUpdates({
cell.photosCollectionView.insertItems(at: collectionViewInserts)
}, completion: nil)
}
}
extension MainViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return PhotosStore.shared.photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
cell.photoImageView.downloadedFrom(link: (appSettings.url + "/resources/img/wp/prev/" + PhotosStore.shared.photos[indexPath.item].fileName))
return cell
}
}
PhotosCell:
import UIKit
class PhotosCell : UITableViewCell{
#IBOutlet weak var photosCollectionView : UICollectionView!
}
extension PhotosCell {
func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {
// IF I PLACE A .reloadData() HERE, THEN IT WORKS BUT THEN THE CELL FLICKERS/JUMPS WHEN APPEARING ON SCREEN
let itemSize = 70
photosCollectionView.delegate = dataSourceDelegate
photosCollectionView.dataSource = dataSourceDelegate
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: itemSize, height: itemSize)
photosCollectionView.setCollectionViewLayout(layout, animated: true)
photosCollectionView.tag = row
photosCollectionView.setContentOffset(photosCollectionView.contentOffset, animated:false) // Stops collection view if it was scrolling.
photosCollectionView.reloadData()
}
var collectionViewOffset: CGFloat {
set { photosCollectionView.contentOffset.x = newValue }
get { return photosCollectionView.contentOffset.x }
}
}
What do I wrong? I do update the datasource correctly, I do perform batch updates on the collection view to insert the correct cells..
Updated details:
MainViewController:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Photos on top
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "PhotosCell", for: indexPath) as! PhotosCell
cell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
cell.collectionViewOffset = storedPhotosCollectionViewOffset[indexPath.row] ?? 0
return cell
}
... other cells ...
}
Extension to download images: (I'm sure that's not the problem but just in case)
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
image = nil
if let cachedImage = ImageCache.shared.loadCachedImage(url: url) {
image = cachedImage
return
}
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else {
DispatchQueue.main.async {
self.image = UIImage(named: "imageMissing")
}
return
}
DispatchQueue.main.async {
self.image = image
ImageCache.shared.cacheImage(image: image, url: url)
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
return downloadedFrom(url: url, contentMode: mode)
}
}
First in cellForRowAt
cell.photosCollectionView.reloadData()
return cell
Second you have to note that the image is downloaded ( consider a dummy image for the imageView or set a background to it ) every scroll so use SDWebImage

didSelectItem not being called

My didSelectItemAt method is not being called and nothing is being printed into the console. I have user interaction turned on and I still can not get it to print out anything. I am not sure if my custom PinterestStyle Layout is causing this or if I am missing something. The ultimate goal would be to segue into a detail view controller showing the profile page of the cell selected. I will do that using prepareForSegue however I still can't even get it to print out the name of the cell when tapped.
class PagesCollectionViewController: UICollectionViewController, firebaseHelperDelegate {
var storageRef: StorageReference!{
return Storage.storage().reference()
}
var usersList = [String]()
var authService : FirebaseHelper!
var userArray : [Users] = []
var images: [UIImage] = []
var names: [String] = []
override func viewWillAppear(_ animated: Bool) {
if Global.Location != "" && Global.Location != nil
{
usersList = Global.usersListSent
print(usersList)
self.authService.ListOfUserByLocation(locationName: Global.Location, type: .ListByLocation)
}
}
override func viewDidLoad() {
self.collectionView?.allowsSelection = true
self.collectionView?.isUserInteractionEnabled = true
super.viewDidLoad()
self.authService = FirebaseHelper(viewController: self)
self.authService.delegate = self
setupCollectionViewInsets()
setupLayout()
}
private func setupCollectionViewInsets() {
collectionView!.backgroundColor = .white
collectionView!.contentInset = UIEdgeInsets(
top: 20,
left: 5,
bottom: 49,
right: 5
)
}
private func setupLayout() {
let layout: PinterestLayout = {
if let layout = collectionViewLayout as? PinterestLayout {
return layout
}
let layout = PinterestLayout()
collectionView?.collectionViewLayout = layout
return layout
}()
layout.delegate = self
layout.cellPadding = 5
layout.numberOfColumns = 2
}
func firebaseCallCompleted(data: AnyObject?, isSuccess: Bool, error: Error?, type: FirebaseCallType) {
if(type == .ListByLocation) {
if(isSuccess) {
self.userArray.removeAll()
self.images.removeAll()
self.images.removeAll()
if(data != nil) {
let dataDict = data as! NSDictionary
let keyArray = dataDict.allKeys
for i in 0 ..< keyArray.count {
var dict = NSDictionary()
dict = dataDict.object(forKey: keyArray[i]) as! NSDictionary
self.userArray.append(Users.init(data: dict))
}
}
self.collectionView?.reloadData()
}
else {
print(error?.localizedDescription)
SVProgressHUD.dismiss()
}
}
}
}
extension PagesCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(userArray[indexPath.row].name)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "PagesCollectionViewCell",
for: indexPath) as! PagesCollectionViewCell
cell.nameLabel.text = userArray[indexPath.row].name
if let imageOld = URL(string: userArray[indexPath.row].photoURL){
cell.photo.sd_setImage(
with: imageOld,
placeholderImage: nil,
options: [.continueInBackground, .progressiveDownload]
)
}
return cell
}
}
extension PagesCollectionViewController : PinterestLayoutDelegate {
func collectionView(collectionView: UICollectionView,
heightForImageAtIndexPath indexPath: IndexPath,
withWidth: CGFloat) -> CGFloat {
var image: UIImage?
let url = URL(string: userArray[indexPath.row].photoURL)
let data = try? Data(contentsOf: url!)
image = UIImage(data: data!)
return (image?.height(forWidth: withWidth))!
}
func collectionView(collectionView: UICollectionView,
heightForAnnotationAtIndexPath indexPath: IndexPath,
withWidth: CGFloat) -> CGFloat {
return 30
}
}
Check 2 conditions:-
Make sure you have set delegate to UICollectionView
Make sure Content in PageCollectionCell like image having no user interaction enabled. If image user interaction is enabled then didSelectItemAt will not call.
as Manish Mahajan said a quick fix would be:
in cellForItemAt func set contentView as not clickable
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.contentView.isUserInteractionEnabled = false
return cell
}

Swift: Everything is loading from web in collectionViewCell except image

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.

self sizing collectionView with flowLayout

When I use collectionView without
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.estimatedItemSize = CGSize (width: self.collectionView.frame.width, height: 100)
then all the cells are displayed but when I use flowLayout then cells are not displayed I've been sitting here for a week on this and can not understand why this is happening.
here my code
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.estimatedItemSize = CGSize(width: self.collectionView.frame.width, height: 100)
requestD(url: url)
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return modals.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if modals.count == 0 {
return UICollectionViewCell()
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCellAudio
cell.name?.text = modals[indexPath.row].name
let u = URL(string: "http://www.---.com" + (modals[indexPath.row].ImageViewURL))
cell.ImageView.sd_setImage(with: u, placeholderImage: UIImage(named: "white"),
options: [.continueInBackground,.scaleDownLargeImages]) { (image, error, cacheType, url) in
self.modals[indexPath.row].ImageView = cell.ImageView.image!
}
return cell
}
func requestD(url:String){
var urlRequest = URLRequest(url: URL(string: url)!)
urlRequest.timeoutInterval = 300
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil{
print(error ?? 0)
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : Any]
if let main = json["LIBRARY"] as? [String:[String : Any]]{
for (_, data) in main {
let info = ModalAudio()
info.id = data["ID"] as? String
info.name = data["NAME"] as? String
info.AboutBook = data["DETAIL_TEXT"] as? String
info.ImageViewURL = data["PICTURE"] as! String
self.modals.append(info)
}
}
} catch let error {
print(error)
}
DispatchQueue.main.sync {
self.isMoreDataLoading = false
self.iNumPage += 1
}
}
self.collectionView?.reloadData()
task.resume()
}
In the viewDidLoad the frame of your collection view is undefined yet, so put this code in your viewDidLayoutSubView method, after reviewing your project your issues is related to use of flowLayout.estimatedItemSize as you can read in the property declaration comment
#available(iOS 8.0, *)
open var estimatedItemSize: CGSize // defaults to CGSizeZero - setting a non-zero size enables cells that self-size via -preferredLayoutAttributesFittingAttributes:
So use this code, it works!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
//flowLayout.estimatedItemSize = CGSize(width: self.collectionView.frame.width, height: 100) don't show your cells
flowLayout.itemSize = CGSize(width: self.collectionView.frame.width, height: 100)//show your cells
flowLayout.invalidateLayout()
}
Hope this helps

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

Resources