我正在制作一款应用程序,用户可以上传不同类型服装项目的照片,并将其显示在Collection 视图中.用户可以点击下拉菜单中的一个按钮,告诉程序图像应该放在哪个部分下.我最初只需要一个集合视图.但现在我决定扩展到多个,但我只有一个的代码.有没有一种好的方法来调整我已经编写的代码,使其他集合视图具有与第一个相同的行为?

//
//  ViewController.swift
//  ugh as if
//
//

import UIKit
import PhotosUI
import Photos
import CoreData
import Foundation
import SwiftUI

// user images below
var imageIDs = [String]()
var countImage = Int()
var currentImageType = String()

class ViewController: UIViewController, PHPickerViewControllerDelegate {

    // when trash is pressed in ClsoetDetailViewController, return to ViewController
    @IBAction func unwindToCloset(segue: UIStoryboardSegue) {
        self.collectionView.reloadData()
    }
    
    
    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet var outerwearCollectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        
        // popup menu items
        let tops = UIAction(title: "tops") { (action) in
              print("tops!")
            self.addPhotos(categoryType: "tops")
         }
         let outerwear = UIAction(title: "outerwear") { (action) in
             print("outerwear!")
             self.addPhotos(categoryType: "outerwear")
         }
         let bottoms = UIAction(title: "bottoms") { (action) in
              print("bottoms!")
             self.addPhotos(categoryType: "bottoms")
         }
        let singles = UIAction(title: "one pieces") { (action) in
             print("singles!")
            self.addPhotos(categoryType: "singles")
        }
        let accessories = UIAction(title: "accessories") { (action) in
             print("accessories!")
            self.addPhotos(categoryType: "accessories")
        }
        let shoes = UIAction(title: "shoes") { (action) in
             print("shoes!")
            self.addPhotos(categoryType: "shoes")
        }
        let menu = UIMenu(title: "my closet", options: .displayInline,
                           children: [tops , outerwear , bottoms, singles, shoes, accessories])
        
        // set up collection in closet
        // navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPhotos))
        navigationItem.rightBarButtonItems = [UIBarButtonItem(systemItem: .add, menu: menu)]
        
        collectionView.register(ClosetCollectionViewCell.nib(), forCellWithReuseIdentifier: "ClosetCollectionViewCell")
        
        // layout.minimumInteritemSpacing = 0
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 75, height: 100)
        layout.minimumLineSpacing = 15
        
        collectionView.collectionViewLayout = layout
        
        collectionView.delegate = self
        collectionView.dataSource = self
    
        collectionView.reloadData()
    }
    
    
    // access photo library
    @objc private func addPhotos(categoryType: String) {
        var config = PHPickerConfiguration()
        config.selectionLimit = 100
        config.filter = .images
        let vc = PHPickerViewController(configuration: config)
        vc.delegate = self
        present(vc, animated: true)
        currentImageType = categoryType
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true, completion: nil)
        let group = DispatchGroup()
        results.forEach { result in
            group.enter()
            result.itemProvider.loadObject(ofClass: UIImage.self) { reading, error in
                defer {
                    group.leave()
                }
                guard let image = reading as? UIImage, error == nil else {
                    return
                }
                
                countImage += 1
                print(countImage)
                
                imageIDs.append(String(countImage))
                print(imageIDs)
                
                LocalFileManager.instance.saveImage(image: image, imageName: String(countImage), folderName: currentImageType)
            }
        }
        group.notify(queue: .main) {
            self.collectionView.reloadData()
        }
    }

}

extension ViewController: UICollectionViewDelegate {
func collectionView(\_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
print("you tapped me!")
// set closetImageName in ClosetDetailViewController
detailImageName = imageIDs\[indexPath.row\]

        print(imageIDs[indexPath.row])
        performSegue(withIdentifier: "closetDetail", sender: nil)
    }

}

extension ViewController: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // how many cells are shown? based on number of items the user uploaded
        return countImage
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // return cell for given item
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ClosetCollectionViewCell", for: indexPath) as! ClosetCollectionViewCell
        // show every cell in image array
        cell.imageView.image = LocalFileManager.instance.getImage(imageName: imageIDs[indexPath.row], folderName: "tops")
        return cell
    }

}

extension ViewController: UICollectionViewDelegateFlowLayout {
// margin of padding between cells
func collectionView(\_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -\> CGSize {
return CGSize(width: 75, height: 100)
}

}

下面是Collection 视图的样子,但与我现在拥有的,所有的照片只被发送到"TOPS"Collection

collection views preview!

我仍然是Xcode的新手,而且只用了几个月,所以如果有任何帮助,我将不胜感激!

我试着复制和编辑扩展(如下所示)中的功能,这样我就可以将不同的照片发送到不同的位置,但它一直向我抛出错误.

extension ViewController: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // how many cells are shown? based on number of items the user uploaded
        return countImage
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // return cell for given item
        if collectionView == self.collectionView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ClosetCollectionViewCell", for: indexPath) as! ClosetCollectionViewCell
            // show every cell in image array
            cell.imageView.image = LocalFileManager.instance.getImage(imageName: imageIDs[indexPath.row], folderName: "tops")
            return cell
        }
        else {
            let cell = outerwearCollectionView.dequeueReusableCell(withReuseIdentifier: "ClosetCollectionViewCell", for: indexPath) as! ClosetCollectionViewCell
            cell.imageView.image = LocalFileManager.instance.getImage(imageName: imageIDs[indexPath.row], folderName: "outerwear")
            return cell
        }
    }
}

推荐答案

您的当前集合视图仅使用了%1节.您可以在您拥有的集合视图中使用多个节,而不是添加多个集合视图.您只需要将数据源从一个数组组织成一个array.

您将需要调整详细信息,但假设您的数据变为:

var images = [[UIImage]]() // Or an array of array of image ids

然后,您的集合视图方法如下所示:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return images.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images[section].count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = ... // however you get a cell
    cell.imageView.image = images[indexPath.section][indexPath.item]

    return cell
}

为其他方法延续这一一般模式.

如果需要显示类别标题或其他内容,可以使用部分标题设置集合视图.

如果功能基本相同,这比添加多个集合视图要简单得多.

Swift相关问答推荐

在用户将输入保存到SWIFT中的核心数据后,如何创建指向我的应用程序S主页的链接?

显示第二个操作紧接在另一个操作后的工作表在SwiftUI中不起作用

是否在核心数据中使用Uint?

仅使用@MainActor注释类的部分时的并发问题

如何为我的项目设置生命周期选项?

如何根据 DatePicker 中选定的日期实现 TabView 页面切换?

是否有一个带有空初始值设定项的 Swift 类/ struct 的标准协议

如何更新 UserDefault 中的特定值

如何为 Swift UI 视图定义 struct ?

从 Swift 列表中的行中检索值

如何 for each 用户制作一个单独的按钮,以便在按下它时切换 isFollowingUser Bool 并更改为关注?

单击按钮后的计时器发布者初始化计时器

来自数据的 SwiftUI 图像

如何删除标签和步进按钮之间的间距是 SwiftUI Stepper?

使用 swift 运行 pod install 时出错

Xcode 6 中的嵌入式内容包含 Swift 代码构建设置有什么作用?

Swift if 语句 - 多个条件用逗号分隔?

Facebook SDK 4.0 IOS Swift 以编程方式注销用户

Void 函数中意外的非 Void 返回值 (Swift 2.0)

Swift performSegueWithIdentifier 不起作用