abdo
abdo

Reputation: 93

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

Upvotes: 1

Views: 517

Answers (2)

Yonatan Vainer
Yonatan Vainer

Reputation: 453

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 enter image description hereimage.

Upvotes: 1

RPatel99
RPatel99

Reputation: 8116

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

Upvotes: 1

Related Questions