首页 > 解决方案 > 如何在 Swift 中将表格视图更改为集合视图?

问题描述

我目前正在做一个研究项目,我正在尝试将表格视图更改为集合视图。我的ViewController继承自UICollectionViewController现在,我还有一个名为的自定义类DetailViewController,它基本上在点击表格行时全屏显示光盘中的图像,这个自定义类继承自UIViewController现在。

import UIKit

class ViewController: UICollectionViewController {
    var pictures = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Storm Viewer"
        navigationController?.navigationBar.prefersLargeTitles = true

        let fm = FileManager.default
        let path = Bundle.main.resourcePath!
        let items = try! fm.contentsOfDirectory(atPath: path)

        for item in items {
            if item.hasPrefix("nssl") {
                pictures.append(item)
            }
        }
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count
    }
        


    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Picture", for: indexPath)
        return cell
    }


    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
            vc.selectedImage = pictures[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

我已经改变了这里的方法。

这是我的自定义类:

import UIKit

class DetailViewController: UIViewController {
    @IBOutlet var imageView: UIImageView!
    var selectedImage: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        title = selectedImage
        navigationItem.largeTitleDisplayMode = .never

        if let imageToLoad = selectedImage {
            imageView.image  = UIImage(named: imageToLoad)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.hidesBarsOnTap = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.hidesBarsOnTap = false
    }
}

我还删除了当前的导航控制器 -> 表格视图控制器 -> 和UIAlertController,并将其替换为 acollectionViewController并将其嵌入到导航控制器中。

而且我在想我真的需要那个细节视图控制器吗,因为我应该能够将我的应用程序包中的图像数据直接提取到集合视图单元格中,并且我正在考虑创建一个自定义的 Cocoatouch集合视图单元的类。我应该删除那个详细视图控制器类吗?

感谢您提前提供任何帮助。

标签: swiftuitableviewuicollectionviewuikit

解决方案


推荐阅读