Collectionviewcell only showing in one of the tab item - swift

I have my storyboard set up such that
Tab bar controller -> nav bar controller 1, nav bar controller 2 -> CollectionView controller 1, CollectionView controller 2
The content inside my collectionviews are basically database i get from firebase (which is working fine). It's just when I start up my app, I can't see the cells in the first collectionview but I can see the cells in my second collectionview. Also, I added a print statement and a segue when you click on a cell and this actually works on both collectionviews. I just can't see the content (just a label) of my collectionviewcell in the first collectionview (the first tab item).
This is the code for my first tab bar item
import Foundation
import UIKit
import Firebase
class SaleListViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let rootref = FIRDatabase.database().reference()
let storage = FIRStorage.storage()
var item_names = [String]()
var item_image_urls = [String]()
var item_details = [Dictionary<String, String>]()
var group = DispatchGroup()
var processRunning = false
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.load_data()
}
/**
Call the firebase function
*/
func load_data(){
self.group.enter()
self.processRunning = true
get_firebase_data(){
if(self.processRunning){
self.processRunning = false
self.group.leave()
}
}
self.group.notify(queue: DispatchQueue.main, execute: {
print("done")
})
}
/**
Get data from firebase database
- parameter completionHandler: Function to be called once it's finished
*/
func get_firebase_data(completionHandler: () -> ()){
rootref.child("Sale").observe(.value, with: { (snapshot) in
if(snapshot.exists()){
var item_data = snapshot.value! as! Dictionary<String, AnyObject>
for(type_2_container,item_list) in item_data{
for(uid_container, item_detail_container) in item_list as! Dictionary<String, AnyObject>{
for(uid, item_detail) in item_detail_container as! Dictionary<String, AnyObject>{
var item_detail_dict = item_detail as? Dictionary<String,String>
var item_detail_temp = Dictionary<String, String>()
for key in (item_detail_dict?.keys)!{
item_detail_temp[key] = item_detail_dict?[key]
}
item_detail_temp["user_id"] = uid
self.item_details.append(item_detail_temp)
if(!self.item_names.contains(item_detail_dict!["item_name"]!)){
self.item_names.append(item_detail_dict!["item_name"]!)
self.item_image_urls.append(item_detail_dict!["item_image"]!)
}
}
}
}
print(self.item_details)
self.collectionView?.reloadData()
print("data was reloaded")
}
})
completionHandler()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.item_details.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:SellcollectViewCellController = collectionView.dequeueReusableCell(withReuseIdentifier: "CellSale", for: indexPath) as! SellcollectViewCellController
cell.cell_name_sale.text = self.item_details[indexPath.row]["item_name"]
print(cell.cell_name_sale.text)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selected")
self.performSegue(withIdentifier: "toDetail", sender: self.item_details[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toDetail"){
let nextVC = segue.destination as! ShowDetailsViewController
let item_details = sender as! Dictionary<String, String>
nextVC.item_details = item_details
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
Signs out a user when the button linked with the IBAction is clicked.
- parameter sender: Object that sent the action message
*/
#IBAction func log_out(_ sender: Any) {
do{
try! FIRAuth.auth()!.signOut()
self.performSegue(withIdentifier: "logout", sender: nil)
print("user logged out!")
} catch {
print("error")
}
}
}
And this is my second tab bar item
import Foundation
import UIKit
import Firebase
class BuyListViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {
let rootref = FIRDatabase.database().reference()
let storage = FIRStorage.storage()
var item_names = [String]()
var item_image_urls = [String]()
var item_details = [Dictionary<String, String>]()
var group = DispatchGroup()
var processRunning = false
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.load_data()
}
func load_data(){
self.group.enter()
self.processRunning = true
get_firebase_data(){
if(self.processRunning){
self.processRunning = false
self.group.leave()
}
}
self.group.notify(queue: DispatchQueue.main, execute: {
print("done")
})
}
func get_firebase_data(completionHandler: () -> ()){
rootref.child("Buy").observe(.value, with: { (snapshot) in
print("inside buy firebase")
if(snapshot.exists()){
var item_data = snapshot.value! as! Dictionary<String, AnyObject>
for(type_2_container,item_list) in item_data{
for(uid_container, item_detail_container) in item_list as! Dictionary<String, AnyObject>{
for(uid, item_detail) in item_detail_container as! Dictionary<String, AnyObject>{
var item_detail_dict = item_detail as? Dictionary<String,String>
var item_detail_temp = Dictionary<String, String>()
for key in (item_detail_dict?.keys)!{
item_detail_temp[key] = item_detail_dict?[key]
}
item_detail_temp["user_id"] = uid
self.item_details.append(item_detail_temp)
if(!self.item_names.contains(item_detail_dict!["item_name"]!)){
self.item_names.append(item_detail_dict!["item_name"]!)
self.item_image_urls.append(item_detail_dict!["item_image"]!)
}
}
}
}
print(self.item_details)
self.collectionView?.reloadData()
print("data was reloaded")
}
})
completionHandler()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.item_details.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:BuycollectViewCellController = collectionView.dequeueReusableCell(withReuseIdentifier: "CellBuy", for: indexPath) as! BuycollectViewCellController
cell.cell_name_buy.text = self.item_details[indexPath.row]["item_name"]
print(cell.cell_name_buy.text)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selected")
self.performSegue(withIdentifier: "toDetail", sender: self.item_details[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toDetail"){
let nextVC = segue.destination as! ShowDetailsViewController
let item_details = sender as! Dictionary<String, String>
nextVC.item_details = item_details
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func log_out(_ sender: Any) {
do{
try! FIRAuth.auth()!.signOut()
self.performSegue(withIdentifier: "logout", sender: nil)
print("user logged out!")
} catch {
print("error")
}
}
}
This is my custom collection view cell controller for the first tab item
import UIKit
class SellcollectViewCellController: UICollectionViewCell {
#IBOutlet weak var cell_name_sale: UILabel!
}
This is the second collection view cell controller
import UIKit
class BuycollectViewCellController: UICollectionViewCell {
#IBOutlet weak var cell_name_buy: UILabel!
}
This is a screenshot of my tab bar controller with the two tab items
Screenshot of the first bar item

Related

In my view collection I added a search bar and it filtered the cells but when I click the cell it it self it the path didn't change

In my view collection I added a search bar and it filtered the cells but when I click the cell it self the path didn't change the path remain the same as it was before the search .
When I click the cell, it should take you to a specific page. Excuse my poor code but I just started to learn swift. And my problem might be super easy and obvious so bare with me please
This is my code I'm using swift storyboard
import UIKit
import Firebase
import FirebaseStorage
class resViewViewController: UIViewController, UISearchBarDelegate, UISearchDisplayDelegate
{
#IBOutlet weak var background: UIImageView!
#IBOutlet weak var icon: UIImageView!
#IBOutlet weak var resL: UILabel!
#IBOutlet weak var collection: UICollectionView!
var resources:[resFile] = []
let db = Firestore.firestore()
//dummy data
#IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var filtered:[resFile] = []
override func viewDidLoad() {
super.viewDidLoad()
let nipCell = UINib(nibName: "resourceCellCollectionViewCell", bundle: nil)
//
collection.delegate = self
collection.dataSource = self
searchBar.delegate = self
///
collection.register(nipCell, forCellWithReuseIdentifier: "cell")
loadResources()
}
func loadResources(){
db.collection("Resources").getDocuments { querySnapshot, error in
if let e = error {
print("There was an issue retrieving data from fireStore. \(e)")
}else {
if let snapshotDocuments = querySnapshot?.documents{
for doc in snapshotDocuments{
let data = doc.data()
if let rName = data["ResName"] as? String, let aName = data["authorName"] as? String, let pName = data["pubName"] as? String, let desc = data["desc"] as? String, let urlName = data["url"] as? String {
let newRes = resFile(name: rName, author: aName, publisher: pName, desc: desc, urlString: urlName)
self.resources.append(newRes)
DispatchQueue.main.async {
self.collection.reloadData()
}
}
}
// DispatchQueue.main.async {
// self.collection.reloadData()
// }
}
}
}
}//end loadResources
//search
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false;
self.searchBar.endEditing(true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
self.searchBar.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
self.searchBar.endEditing(true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = resources.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.collection.reloadData()
}
}//end of class
extension resViewViewController:UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = (UIScreen.main.bounds.size.width - 110)/2
return CGSize(width: w, height: 160) //154
}//end size
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
} else {
return resources.count
}
}//end count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! resourceCellCollectionViewCell
if(searchActive) {
cell.name.text = filtered[indexPath.row].name
} else {
cell.name.text = resources[indexPath.row].name
}
return cell
}//end cell
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "si_resourceListToDetail", sender: indexPath)
}//end
}//extention
extension resViewViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "si_viewResToPost", let vc = segue.destination as? resPostViewController {
vc.delegate = self
} else if segue.identifier == "si_resourceListToDetail",
let vc = segue.destination as? detailedResViewController, let indexPath = sender as? IndexPath {
vc.resource = resources[indexPath.row]
}
}
}//extension
extension resViewViewController: resPostViewControllerDelegate {
func resPost(_ vc: resPostViewController, resource: resFile?, added: Bool){
vc.dismiss(animated: true) {
if added, let r = resource {
self.resources.append(r)
self.collection.reloadData()
}
}
}
}//extension
The indexPath will always be the same if you select the first visible cell in the UICollectionView. You must check the underlying data set to get the difference..
Also: In Swift it's convention to have capital first letter of classes and structs.
You must do something like this to achieve what you want:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item: ResFile
if searchActive {
item = filtered[indexPath.item]
} else {
item = resources[indexPath.item]
}
performSegue(withIdentifier: "si_resourceListToDetail", sender: item)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let item = sender as? ResFile else { return }
// Send item to destination view controller
}

How do I pass information to a new view controller using a segue in swift

I'm running into a problem while working on a simple project. This app essentially just displays a collection of images and when I tap one of the images, it is suppose to transition into a new view controller and display the name of the image on a label.
I am new at Swift. Is it something to do with the indexPath that I used in the function to fill the collection view? I tried to see if I could get the indexPath and then pass that into the images array to get the name and send the name in the second view controller but it comes up nil. Any help would be greatly appreciated
This is my CollectionViewController
class ImagePickerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet var collectionView: UICollectionView!
var images = Data()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as? CollectionViewCell {
cell.imageView.image = UIImage(named: "\(images.images[indexPath.item])")
return cell
}
return UICollectionViewCell()
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? FeedPickerViewController{
if segue.identifier == "detailViewController_segue"{
let cell = sender as! CollectionViewCell
let indexPath = self.collectionView.indexPath(for: cell)
let imgName = images.images[indexPath!.item]
dest.imgName = imgName
}
}
}
}
This is theViewController that I am segueing to
class DetailViewController: UIViewController {
var imgName: String!
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Posting Image: \(imgName)"
}
}
and this is the data class
class Data {
let images = ["bear", "bird", "bridge",
"cabin"]
}
You should remember indexPath which is selected cell's
You can use collectionView:didSelectItemAtIndexPath: to retrieve selected cell's indexPath
selectedIndexPath = indexPath
then pass the data of the selected using selected IndexPath to destination view controller
dest.imageName = images.images[selectedIndexPath!.item]
Try this one
class ImagePickerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet var collectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return DataImage.images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as? CollectionViewCell {
cell.imageView.image = UIImage(named: DataImage.images[indexPath.item])
return cell
}
return UICollectionViewCell()
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? FeedPickerViewController{
if segue.identifier == "detailViewController_segue"{
let cell = sender as! CollectionViewCell
let indexPath = self.collectionView.indexPath(for: cell)
let imgName = DataImage.images[indexPath!.item]
dest.imgName = imgName
}
}
}
}
class DetailViewController: UIViewController {
var imgName: String!
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Posting Image: " + imgName
}
}
Use struct instead of Class
struct DataImage {
static var images = ["bear", "bird", "bridge", "cabin"]
}

How to use NSPredicate to fetch request and populate second viewController with data when UItableView roll is pressed in first viewController

I'm coding a Note App in Swift 4. The root ViewController (NoteListViewController) gets populated when secondViewController (ComposeNoteViewController) Textfield and TextView are populated.
The problem is when I press a populated TableView cell, rather than fetch and display the content, it opens a fresh instance of theComposeNoteViewController.
import UIKit
import CoreData
class NoteListTableViewController: UITableViewController {
var noteListArray = [NoteListItem]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
loadNoteListItem()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return noteListArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoteListItemCell", for: indexPath)
cell.textLabel?.text = noteListArray[indexPath.row].title
return cell
}
//MARK: - TABLEVIEW DELEGATE METHODS
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToComposeNote", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ComposeNoteViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedNoteList = noteListArray[indexPath.row]
}
}
import UIKit
import CoreData
class ComposeNoteViewController: UIViewController {
var noteComposeItemsArray = [ComposeNote]()
var noteListArray = [NoteListItem]()
// let noteListController = NoteListTableViewController()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var selectedNoteList : NoteListItem? {
didSet {
loadComposeItem()
}
}
#IBOutlet weak var noteTextView: UITextView!
#IBOutlet weak var noteTextField: UITextField!
#IBAction func noteSavePressed(_ sender: UIBarButtonItem) {
let newNoteTitleItem = NoteListItem(context: context)
let newComposeNote = ComposeNote(context: context)
newNoteTitleItem.title = noteTextField.text!
newComposeNote.note = noteTextView.text!
newComposeNote.parentTitleNote = selectedNoteList
noteComposeItemsArray.append(newComposeNote)
noteListArray.append(newNoteTitleItem)
saveComposeItems()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func saveComposeItems() {
do {
try context.save()
}catch {
print("Error saving context \(error)")
}
reloadInputViews()
}
func loadComposeItem() {
let request : NSFetchRequest<ComposeNote> = ComposeNote.fetchRequest()
let predicate = NSPredicate(format: "parentTitleNote.title MATCHES %#", selectedNoteList!.title!)
request.predicate = predicate
do {
noteComposeItemsArray = try context.fetch(request)
}catch {
print("Can't load Items")
}
reloadInputViews()
}
}

Pass data from CollectionviewCell to ViewController

when i write the function touchphoto, the post.postID is nil .I want to pass the postID to another view controller. I add the code for the profilecell and profileviewcontroller
protocol profilecellDelegate {
func goToPhotoDetail(postid: String)}
class profilecell: UICollectionViewCell {
var delegate: profilecellDelegate?
#IBOutlet weak var image: UIImageView!
var post: Post? {
didSet {
updateView()
}
}
func updateView() {
if let photoUrlString = post?.photoUrl {
let photoUrl = URL(string: photoUrlString)
image.sd_setImage(with: photoUrl)
}
}
#IBAction func touchphoto(_ sender: Any) {
if let id = post?.postID {
delegate?.goToPhotoDetail(postid: id)
}
}
}
//profileviewcontroller
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "profilecell", for: indexPath) as! profilecell
let post = posts[indexPath.row]
cell.post = post
cell.delegate = self
return cell
}
extension ProfileViewController: profilecellDelegate {
func goToPhotoDetail(postid: String) {
performSegue(withIdentifier: "Photo_ProfileSegue", sender: postid)
}}

accessing an array of images from 1 view controller to another, to add swipe gesture recognizer

i have a collection view which has an array of images. when i press on any of the images it will open that image in full screen in another class. i tried to add swipe gesture recognizer in the second view controller but i dont know how to access the array that is in the first view controller.
This is my first view controller that displays the images in collection view
class sowrController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
#IBOutlet weak var collectionView: UICollectionView!
var albums = [AlbumModel]()
let db : DBHelperMo2lfat = DBHelperMo2lfat()
var selectedIndex : Int = -1
var posts : Post!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
self.albums.removeAll()
self.albums.append(contentsOf: self.db.fetchAllImages())
self.collectionView.reloadData()
DataService.ds.REF_POSTS_SOWR.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.albums.removeAll()
for snap in snapshot {
print ("SNAP: \(snap)")
if let postDict = snap.value as? Dictionary<String, AnyObject>{
let album : AlbumModel = AlbumModel(id: postDict["id"] as! String, name: postDict["image_name"] as! String, path: postDict["image_path"] as! String, url: postDict["image_path"] as! String, localPath: "")
if let items = snap.children.allObjects as? [FIRDataSnapshot] {
for itemSnap in items {
if let albumSnap = itemSnap.value as? Dictionary<String, AnyObject> {
album.childAlbums.append(AlbumModel(id: albumSnap["id"] as! String, name: albumSnap["image_name"] as! String, path: albumSnap["image_path"] as! String, url: albumSnap["image_path"] as! String, localPath: ""))
}
}
}
self.albums.append(album)
}
}
self.collectionView.reloadData()
}
})
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.albums.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.BookCellReuseIdentifier, for: indexPath) as? collectionViewCellSowr {
let album = albums[indexPath.item]
cell.initWithAlbumModel(album: album)
return cell
}else {
return collectionViewCellSowr()
}
}
private struct Constants {
static let BookCellReuseIdentifier = "cell"
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectedIndex = indexPath.row
self.performSegue(withIdentifier: "showAlbum", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "showAlbum"
{
let vc = segue.destination as! imageFullScreen
vc.images = self.albums[self.selectedIndex]
}
}
This is the second view controller that makes the images go in full screen
class imageFullScreen: UIViewController{
var images : AlbumModel?
let db : DBHelperMo2lfat = DBHelperMo2lfat()
#IBAction func pictureSwipe(_ sender: Any) {
}
#IBOutlet weak var caption: UILabel!
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.caption.text = images?.imageName
let url = URL(string: (images?.imagePath)!)
self.imageView.sd_setImage(with: url, placeholderImage: nil, options: [.progressiveDownload,.retryFailed])
}
EDIT:
Ok, so here is a collection view controller that creates image view as a subview and responding to swipe gestures. Please make sure you have two images "Image" and "Image-1" in your assets folder.
//
// CollectionViewController.swift
// test
//
// Created by Yonatan Vainer on 05/08/2017.
// Copyright © 2017 Sensus Healthcare LLC. All rights reserved.
//
import UIKit
private let reuseIdentifier = "id"
class CollectionViewController: UICollectionViewController {
var imageView = UIImageView(frame: CGRect(x: 0, y: 100, width: 300, height: 300))
var index = 0;
let names = ["Image","Image-1"]
override func viewDidLoad() {
super.viewDidLoad()
//For left swipe
let left = UISwipeGestureRecognizer(target: self, action: #selector(self.goLeft(_:)))
left.direction = .left
imageView.addGestureRecognizer(left)
//For right swipe
let right = UISwipeGestureRecognizer(target: self, action: #selector(self.goRight(_:)))
right.direction = .right
imageView.addGestureRecognizer(right)
imageView.isUserInteractionEnabled = true
self.view.addSubview(imageView)
self.view.layoutSubviews()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
// 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 names.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
let nail = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
nail.image = UIImage(named: names[indexPath.row])
cell.backgroundView = nail
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
imageView.image = UIImage(named: names[indexPath.row])
index = indexPath.row
}
func goLeft(_ gesture: UISwipeGestureRecognizer){
index += 1
if index<0{
index = 0
}
imageView.image = UIImage(named: names[index])
}
func goRight(_ gesture: UISwipeGestureRecognizer){
index -= 1
if index>1{
index = 1
}
imageView.image = UIImage(named: names[index])
}
// 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?) {
}
*/
}
==================================================================
In storyboard, click on your collection view and embed navigation controller.
This will add a top bar with the back button.
Attached image.
I'm not sure I completely understand your question, because I don't understand what the array has to do with a gesture recognizer, but if you are just trying to access the array from the previous ViewController, this should work if you have a navigation controller :
let vcIndex = self.navigationController?.viewControllers.index(where: { (viewController) -> Bool in
if let _ = viewController as? sowrController {
return true
}
return false
})
let prevVC = self.navigationController?.viewControllers[vcIndex!] as! sowrController
let albums:[AlbumModel] = prevVC.albums