how to pass data in perform segue sender through protocol & delegate from a UICollectionViewCell inside UITableViewCell? - uitableview

I have VC(a) with TableView
Inside the UITableViewCell.xib I installed a UICollectionView
UICollectionViewCell registered inside the UITableViewCell.xib of
course.
I want to perform segue from VC(a) to VC(b) when UICollectionViewCell didSelected
And since the UICollectionViewCell is registered inside the
UITableViewCell.xib so I can't use performSegue(withIdentifier:
String, sender: Any) inside the .xib file because it is not
inherited from UIViewController
I did some searches in StackOverFlow and I found methods to perform segue by creating a custom delegator protocol I applied the protocol and everything seems OK except the sender!!
I know how to use it inside VC without protocol but I don't know how to use it after applying the protocol
I'm new to Swift Language and so please help me to complete my code
Here below is the UITableViewCell.xib code
protocol MyCustomCellDelegator {
func cellWasPressed()
}
class AdminPList_TableViewCell: UITableViewCell {
var delegate: MyCustomCellDelegator?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setupCell()
getFProducts()
}
#IBOutlet weak var CollectionView: UICollectionView!
func getFProducts() {
productAPI.GetAllproducts { (appendThisProduct) in
self.FP_Array.append(appendThisProduct)
self.CollectionView.reloadData()
}
}
var FP_Array : [productObject] = []
}
extension AdminPList_TableViewCell : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func setupCell() {
CollectionView.delegate = self ; CollectionView.dataSource = self
CollectionView.register(UINib(nibName: "FproductsCell", bundle: nil), forCellWithReuseIdentifier: "FPcell")
// CollectionView.register(UINib(nibName: "TproductsCell", bundle: nil), forCellWithReuseIdentifier: "TPcell")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.CollectionView.frame.size.width-10, height: self.CollectionView.frame.size.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { // make spacing between each cell
return 10
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return FP_Array.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let FPcell = CollectionView.dequeueReusableCell(withReuseIdentifier: "FPcell", for: indexPath) as! FproductsCell
FPcell.UpdateFP_cell_Content(RetrivedProducts: FP_Array[indexPath.row])
return FPcell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedProduct = FP_Array[indexPath.row] // I want to pass it to sender in perform segue un ProductsLibrary Class
// print (selectedProduct.productName)
self.delegate?.cellWasPressed()
}
}
Help me to pass selectedProduct to perform segue in below protocol
And here below is the VC(a) where the UITableView is installed:
class ProductsLibrary : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupCell()
}
#IBOutlet weak var TableView: UITableView!
}
extension ProductsLibrary : UITableViewDelegate, UITableViewDataSource, MyCustomCellDelegator {
func cellWasPressed(withData: productObject) {
performSegue(withIdentifier: "EditProduct", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let next = segue.destination as? ProductManagement{
print ("Editing Product is Active")
let product = sender as? productObject
print(product) //it shows nil !!!
next.EditingProduct = product
}
}
func setupCell() {
TableView.delegate = self ; TableView.dataSource = self
TableView.register(UINib(nibName: "AdminPList_TableViewCell", bundle: nil), forCellReuseIdentifier: "PLcell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PLcell", for: indexPath) as! AdminPList_TableViewCell
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.TableView.frame.size.height/3
}
}

When I started learning the delegation pattern I always made some mistakes. So I make a rule for myself. When you have to implement a delegate always remind 6 steps.
The First 3 steps are for the class that will pass the data or write protocol, here your AdminPList_TableViewCell is that class. The 3 steps are
Write a protocol (a bunch of method declaration) // you did it.
Declare a protocol variable inside the class that will pass the data. // you did that too (var delegate: MyCustomCellDelegator?)
Call the methods you declared. // you did that (self.delegate?.cellWasPressed())
The Last 3 steps are for the class that will conform that protocol, here ProductsLibrary is that class.
Conform that protocol in that class which will implement those methods. // here you did that (extension ProductsLibrary: ..., MyCustomCellDelegator)
Assign delegate to self, but what is self here? well, self is the ProductsLibrary which has been delegated! // you missed that
Implement the protocol methods. // you did that :)
How to solve this?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.delegate = self // you missed this line
...
return cell
}
Now for passing selectedProduct just change the protocol method definition everywhere.
protocol MyCustomCellDelegator {
func cellWasPressed(withData: productObject)
}
Then call from the didSelectItemAt method
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedProduct = FP_Array[indexPath.row] // I want to pass it to sender in perform segue un ProductsLibrary Class
self.delegate?.cellWasPressed(withData: selectedProduct)
}
Now use it inside the method body.
func cellWasPressed(withData data: productObject) {
//now use the data and write your necessary code.
performSegue(withIdentifier: "EditProduct", sender: self)
}
Hope it will help you :).

how are you?
Maybe your delegate is nil, and thats why you func callWasPressed() didn't called.
You need to set delegate on VC after instantiate your cell.
Like this:
AdminPList_TableViewCell.delegate = self
I hope it helped you!
Happy coding =D

To pass object through other VC you need to follow these 3 steps:
1st: Create a var on your new VC:
var selectedObject: YourKindObject?
2nd: Pass your object to sender like this:
func cellWasPressed(withData data: productObject) {
// pass productObject as sender
performSegue(withIdentifier: "EditProduct", sender: productObject)}
3rd: On your override method, you should capture your segue ID and passthroug object, like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourID(Can be setted on storyboard segue identifier))" {
var object = sender as! YourKindObject
let controller = segue.destination as? VC
controller?. selectedObject = object
}
}

Related

Hint on how to create & pass data via segue when collectionview cell is pressed

I have a UICollectionView embedded in a UITableViewCell & I want to perform a segue when a UICollectionViewCell is pressed & pass the data represented by that cell to the destination ViewController for detailed information.
Here is the code for the embedded UICollectionView inside the UITableViewCell
#IBOutlet weak var EventCollection: UICollectionView!
var events = [Events]()
override func awakeFromNib() {
super.awakeFromNib()
EventCollection.delegate = self
EventCollection.dataSource = self
}
extension PopularCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return events.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = EventCollection.dequeueReusableCell(withReuseIdentifier: "EventCell", for: indexPath) as! EventCell
let event = events[indexPath.row]
print("Event Name:\(event.event_name)")
cell.event = event
cell.tag = indexPath.row
return cell
}
How do I perform & prepare a segue in the main ViewController when a UICollectionViewCell is pressed so as to pass the data contained by that cell to the destination ViewController
Here are the steps that you need to do.
As you said, your CollectionView is inside TableView. So your TableView delegates/DataSources binded with the MainViewController. CollectionView delegates/DataSources binded with the TableViewCell.
Now create a protocol to know user has clicked on collectionView.
protocol MyProtocol : class {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
}
In TableViewCell, you need to call delegate like this,
class MyTableCell : UITableViewCell, UICollectionViewDelegate {
weak var delegate : MyProtocol?
:
:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let delegate = delegate {
delegate.collectionView(collectionView, didSelectItemAt: indexPath)
}
}
}
Now your MainViewController must have to conform this protocol,
class MainViewController :UIViewController, MyProtocol {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Do segue here ....
}
}
Note : Make sure to bind delegate with your MainViewController i.e. in TableviewCellForRow have cell.delegate = self
Add the following code with in a new file named UIView_Ext
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
In func didSelectItem(At indexPath: IndexPath) method , write the following code
self.parentViewController?.performSegue(withIdentifier: "Identifer", sender: "Your Data in place of this string")

UICollectionView shouldShowMenuForItemAt Not Called

I have a stock standard UICollectionView in a UIViewController that is its delegate. However the shouldShowMenuForItemAt func is not called for a long press. I have added a didSelectItemAt func which does get called on clicking a cell to make sure the delegate is indeed wired up correctly.
I also implemented the canPerformAction to return true and performAction in the delegate along with the canPerformAction and canBecomeFirstResponder to return true in my UICollectionViewCell subclass. None of these func's get called for a long press of a cell. Any suggestions?
The missing piece of the puzzle, which most people seem to miss, is that in order for menus to work (in a collection view or table view), the cell must implement the selector.
Here's a minimal example. Instruction: Make a new project using the Single View App template. Copy this code and paste it into ViewController.swift, so as to replace completely everything in that file. Run. Long press on a green square. Enjoy. (The menu item does nothing; the point is, you will see the menu item appear.)
import UIKit
class Cell : UICollectionViewCell {
#objc func f(_ : Any) {}
}
class ViewController: UIViewController {
let cellid = "cellid"
#nonobjc private let howdy = #selector(Cell.f)
override func viewDidLoad() {
super.viewDidLoad()
let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
self.view.addSubview(cv)
cv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cv.delegate = self
cv.dataSource = self
cv.register(Cell.self, forCellWithReuseIdentifier: cellid)
}
}
extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ cv: UICollectionView, cellForItemAt ip: IndexPath) -> UICollectionViewCell {
let cell = cv.dequeueReusableCell(withReuseIdentifier: cellid, for: ip)
cell.backgroundColor = .green
return cell
}
func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
let mi = UIMenuItem(title:"Howdy", action:howdy)
UIMenuController.shared.menuItems = [mi]
return true
}
func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return (action == howdy)
}
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
}

Custom UICollectionView Data Source and Delegate

I've been struggling with this for hours as I'm relatively new to XCode and Swift.
I have a CollectionView in my storyboard and want to link its data source and delegate methods to a separate class other than my ViewController but it isn't working.
Can anyone help?
override func viewDidLoad() {
super.viewDidLoad()
//
self.card.center = CGPoint(x: self.view.center.x, y: self.view.center.y)
self.card.layer.cornerRadius = 5
self.card.layer.shadowOpacity = 0.1
//
self.card2.center = CGPoint(x: self.view.center.x, y: self.view.center.y)
self.card2.layer.cornerRadius = 5
self.card2.layer.shadowOpacity = 0.1
//
self.view.bringSubview(toFront: self.card)
// HERE IS THE LINK
setDS()
collectionView.reloadData()
// ----------------------
}
private func setDS() {
let dataSourceAndDelegate = CollectionViewController()
collectionView.dataSource = dataSourceAndDelegate
collectionView.delegate = dataSourceAndDelegate
}
import UIKit
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.red
print("View did load")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in 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
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
cell.backgroundColor = UIColor.blue
return cell
}
// MARK: UICollectionViewDelegate
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> 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, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
}
Don't use subclass of UICollectionViewController as datasource and delegate of your custom collectionview.
Instead use simple NSObject class. That way you would need to implement only the datasource and delegate methods and dont have to worry about UIViewcontroller's view methods(you dont need them anyway).
But even if you provide object of UICollectionViewController it should work. It is not working because you have not retained the object in your ViewController class and it is getting autoreleased. UICollectionView does not retain delgeate and datasource to prevent retain cycles.
let dataSourceAndDelegate = CollectionViewController()
Make dataSourceAndDelegate a stored property.
Also, you would need to register your cell inside ViewController class (because it has the collection view you are working with). Remember collectionView property inside UICollectionViewController is not same as your collectionView in ViewController. It is a stored property because UICollectionViewController comes with a colectionview.
private let reuseIdentifier = "Cell"
class ViewController: UIViewController {
let dataSourceAndDelegate = CollectionViewController()
#IBOutlet var collectionView:UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.setDS()
collectionView.reloadData()
}
private func setDS() {
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.dataSource = dataSourceAndDelegate
collectionView.delegate = dataSourceAndDelegate
}
}

Swift: How to use "didSelectItemAtIndexPath" in UITableViewController(contains UICollectionView)?

I have a UITableViewController, inside the TableViewCell, it's a UICollectionView. I want to pass the data from the CollectionViewCell to a DetailViewController when user tapped the cell. I dragged a segue from the CollectionViewCell to the DetailViewController, and used the didSelectItemAtIndexPath inside the TableViewCell( which contains CollectionView), and it works.
class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var posts1: [Posts] = [Posts]()
var posts2: [Posts] = [Posts]()
var categories: [Category] = [Category]()
var selectedPost1: Posts?
#IBOutlet weak var theCollectionView: UICollectionView!
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts1.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let collectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
let imageUrlString: String = posts1[indexPath.row].postThumbnailUrlString
let imageUrl: NSURL = NSURL(string: imageUrlString)!
//Give Images A round cornor
let filter = AspectScaledToFillSizeWithRoundedCornersFilter(
size: collectionViewCell.postImageView.frame.size,
radius: 20.0
)
collectionViewCell.postImageView.af_setImageWithURL(imageUrl, filter: filter)
collectionViewCell.postTitleLabel.text = posts1[indexPath.row].postTite
return collectionViewCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("selected")
self.selectedPost1 = self.posts1[indexPath.row]
}
it can print "selected" which means the data have already been stored in self.selectedPost1. But I can't use prepareForSegue inside this class, since it can only be used in ViewController. someone told me to implement UICollectionViewDelegate in my HomeTableViewController, and call the function didSelectedItemAtIndexPath in the HomeTableViewController, like this:
import UIKit
class HomePageTableViewController: UITableViewController,UICollectionViewDelegate {
let sections: NSArray = ["latest news", "good news"]
var posts1: [Posts] = [Posts]()
var selectedIndexPath: NSIndexPath?
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < sections.count{
return sections[section] as? String
}
return nil
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 && indexPath.section == 0 {
let tableViewCell = tableView.dequeueReusableCellWithIdentifier("TableViewCell") as! TableViewCell
tableViewCell.getCategories()
// tableViewCell.scrollToNextCell()
// tableViewCell.startTimer()
return tableViewCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("goToDetail", sender: TableViewCell())
print("selected")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let tableViewCell1 = sender as? TableViewCell,
let postDetailPage = segue.destinationViewController as? DetailViewController{
let selectedPosts = tableViewCell1.selectedPost1
postDetailPage.selectedPost?.selectedPost1 = selectedPosts
}
However, the didSelectedItemAtIndexPath can't be called, there is no print. I don't know why?
here is my DetailViewController:
import UIKit
class DetailViewController: UIViewController {
#IBOutlet weak var postImageView: UIImageView!
var posts: [Posts] = [Posts]()
var selectedPost: TableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
if let post = selectedPost?.selectedPost1{
let thumbnailUrlString = post.postThumbnailUrlString
let imageUrl: NSURL = NSURL(string: thumbnailUrlString)!
print(thumbnailUrlString)
postImageView.af_setImageWithURL(imageUrl)
}
}
and also do I need to implement in viewDidLoad or viewDidAppear?
I have been struggled in this problem for few days? need some suggestions on How to do Segue from a UICollectionViewCell (which is inside a UITableViewCell) to a new UIViewController.
The way you are going is correct, but you are creating one mistake.Try to implement UICollectionViewDelegate method didSelectItemAtIndexPath also inside TableViewCell and remove it from the HomePageTableViewController.
Now declare one protocol, after that create its instance inside TableViewCell and implement the protocol in the HomePageTableViewController, after that in the didSelectItemAtIndexPath use that delegate instance to call the method like this.
protocol PostDelegate {
func selectedPost(post: Posts)
}
Now create its instance inside TableViewCell and call this delegate method in the didSelectItemAtIndexPath.
class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var posts1: [Posts] = [Posts]()
var posts2: [Posts] = [Posts]()
var categories: [Category] = [Category]()
var selectedPost1: Posts?
var postDelegate: PostDelegate?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
postDelegate?. selectedPost(self.posts1[indexPath.row])
}
}
Now implement this PostDelegate protocol inside HomePageTableViewController
class HomePageTableViewController: UITableViewController,UICollectionViewDelegate {
//Your code
func selectedPost(post: Posts) {
//You will get your post object here, do what you want now
}
}
Note: Inside cellForRowAtIndexPath don't forgot to set the delegate of postDelgate with your HomePageTableViewController like this
tableViewCell.postDelegate = self
Edit:
func selectedPost(post: Posts) {
//You will get your post object here, do what you want now
self.performSegueWithIdentifier("goToDetail", sender: post)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let post = sender as! Posts
let postDetailPage = segue.destinationViewController as? DetailViewController
postDetailPage.passPost = post
}
So, You have not implemented the
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
...
}
and
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
methods in your second implementation.
Also, try putting an invisible button over the collection view cell and assign the tag to be the indexpath of that collectionview cell like this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
....
myButton.tag = indexpath.item
}
After this you may either implement a delegate callback from collectionviewcell class to the homepagetableviewcontroller class or push the detail view controller directly by code.
As far as setting of image in the detail view controller is concerned. You can do it both in viewdidLoad() or viewDidAppear(). Its fine.

Type does not conform to protocol Swift

Started practicing Swift. In singleViewController I am trying to make a UICollectionView. In storyboard I set the dataSource and delegate. Here I am getting the error:
'UICollectionView' does not conform to protocol 'UICollectionViewDataSource'
import UIKit
class galeriacontroler: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
#IBOutlet weak var collectionview: UICollectionView!
let fotosgaleria = [UIImage(named: "arbol3"), UIImage(named:"arbol4")]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.fotosgaleria.count
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellImagen", forIndexPath:indexPath) as! cellcontroler
cell.imagenView2?.image = self.fotosgaleria[indexPath.row]
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showImage", sender: self )
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showImage"
{
let indexPaths = self.collectionview!.indexPathsForSelectedItems()
let indexPath = indexPaths![0] as NSIndexPath
let vc = segue.destinationViewController as! newviewcontroler
vc.image = self.fotosgaleria[indexPath.row]!
}
}
}
UICollectionViewDataSource has two required methods -
collectionView(_:numberOfItemsInSection:) and collectionView(_:cellForItemAtIndexPath:), of which you have implemented only one.
You need to add an implementation for collectionView(_:cellForItemAtIndexPath:) to fix this problem:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as CollectionCell
... // Do more configuration here
return cell
}
When you import UICollectionViewDataSource you must implement cellForItemAtIndexPath method
Add the following method to your code:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imagesCellIdentifier", forIndexPath:indexPath) as! cellcontroler
cell.secondImageView?.image = self.photosGalleryArray[indexPath.row]
return cell
}
willDisplayCell is not necessary to implement after this.

Resources