从一个视图控制器访问一组图像到另一个视图控制器,以添加滑动手势识别器

Posted

技术标签:

【中文标题】从一个视图控制器访问一组图像到另一个视图控制器,以添加滑动手势识别器【英文标题】:accessing an array of images from 1 view controller to another, to add swipe gesture recognizer 【发布时间】:2017-08-04 21:22:55 【问题描述】:

我有一个包含图像数组的集合视图。当我按下任何图像时,它将在另一个类中全屏打开该图像。我试图在第二个视图控制器中添加滑动手势识别器,但我不知道如何访问第一个视图控制器中的数组。

这是我第一个在集合视图中显示图像的视图控制器

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]

        
    

这是第二个让图像全屏显示的视图控制器

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

【问题讨论】:

【参考方案1】:

编辑:

好的,这是一个集合视图控制器,它将图像视图创建为子视图并响应滑动手势。请确保您的资产文件夹中有两个图像“Image”和“Image-1”。

//
//  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?) 

    
    */


================================================ ====================

在情节提要中,单击您的集合视图并嵌入导航控制器。 这将添加一个带有后退按钮的顶部栏。 附image。

【讨论】:

我要做的是在一组图像之间左右滚动,类似于任何图像库 好的。选项很少。这是一个:在这种情况下,不要使用第二个视图控制器。在集合视图控制器内的任何单元格上单击,以编程方式创建 UIImageView,用您的图像填充它,通过分配宽度和高度使其全屏显示,并将其添加为子视图。然后,当您获得滑动手势时,只需分配不同的图像并重新加载视图。 刚刚更新了我的答案。在我的模拟器上检查它,它工作正常。如果是你需要的,欢迎采纳:)【参考方案2】:

我不确定我是否完全理解你的问题,因为我不明白数组与手势识别器有什么关系,但如果你只是想从以前的 ViewController 访问数组,这应该可以工作 如果你有导航控制器:

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

【讨论】:

@abdo 查看this link。 Duncan C 的答案正是您所需要的。

以上是关于从一个视图控制器访问一组图像到另一个视图控制器,以添加滑动手势识别器的主要内容,如果未能解决你的问题,请参考以下文章

从一个视图控制器访问 CLLocationManager 变量到另一个视图控制器

Swift:通过 TabBar 和导航控制器以编程方式从一个视图转换到另一个视图

如何以编程方式将数据从表视图控制器传递到另一个控制器? [复制]

如何从 popoverpresentation 视图控制器导航到另一个视图控制器

无法使用按钮从一个视图控制器导航到另一个视图控制器

从一个 VC 切换到另一个 VC 时在视图控制器中保留数据