如何将图像从项目中的文件夹添加到collectionview?

How to add images to collectionview from folder in project?

想请问有没有办法从文件夹中解析图片到数组

我有类别:"Colors"、"Buildings" 等,每个类别文件夹中都有相关图片。

我首先需要一个带有类别的 collectionView,点击单元格后我需要用类别中的相关图像填充 collectionView。

首先重命名所有组的图片,按照组名升序排列,如'Barvy_0.jpg'等..

然后声明一个空白字符串,如:

var image_name:String = ""

然后将 image_name 设置为点击按钮时的组名,就像点击 Barvy 按钮一样:

image_name = "Barvy"

在收藏视图中:

cell.imageview.image = UIImage(named:"\(image_name)\(indexPath.row).png")!

您的图像在捆绑文件中,因此您可以直接使用图像名称,如 [UIImage imagedNamed : @"<name.png>"]。您有包含多个图像的文件夹,因此要显示这些图像,您可以执行以下操作:

为您的所有四个文件夹制作包含图像名称的数组,例如 NSArray *arrBravy = @[@"Bravy_cool.png", @"Bravy_angry.png" ... ];。在 collectionView

cell.imgView.image = arrImages[indexPath.row];

arrImages  = arrBravy or arrBudovy... etc , as per the condition user clicked on which option.

但是正如您所说,您有很多文件夹,因此您无法管理多个数组,因此要解决此问题,您需要制作一个 json 文件并将其添加到您的捆绑包中。现在在这个 json 文件上应用序列化,你会得到所有文件的列表。

json 文件的建议模式:

 {
      {
               "folderName": "Bravy",
            "imgList": [ "Bravy_cool", "Bravy_angry", "Bravy_OK"]

      },
      {
             "folderName": "Budovy",
            "imgList": [ "Budovy_kiss", "Budovy_sleep", "Budovy_cry"]

      }
    } 

我刚刚给你举了两个文件夹名称的例子,你可以把它扩展到你的用途。而保持json是处理这类问题的最好办法

如何处理 JSON

获取json数据:

NSArray *arrJson = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

为图像分配 Json

//userSelectedString is string which notifes user selected which folder

for(int i= 0; i< arrJson.count: i++){
  if(arrJson[i][@"folderName"] == @"userSelectedString"){
    arrImages = arrJson[i][@"imgList"];
  }
}

在集合视图 ItemFor Row

cell.imgView.image = arrImage[indexPath.row];

如果你有XML,没关系!您可以像处理 json 数据一样处理 xml,但略有不同。

  1. 如果您想获取 XML 文件,请阅读本教程:https://www.raywenderlich.com/725/xml-tutorial-for-ios-how-to-read-and-write-xml-documents-with-gdataxml

  2. 如果您想将 XML 转换为 Json,请使用此在线转换器并下载您的文件:http://www.utilities-online.info/xmltojson/#.WFTDfuZ97IU

如何在 UICOLLECTIONVIEW 中显示图像

先写这个

@interface myViewController : UIViewController {

    //BOOL isFolderSelected;
    NSMutableArray *arrMutImages;
}

ViewDidLoad

arrMutImages = [NSMutableArray New];
    [arrMutImages addObject:[self getFolderNames]];

创建新方法

- (NSMutableArray *) getFolderNames{
    NSMutableArray *arrMutfetchImage = [NSMutableArray New];
    for(int i=0 ; i < arrJson.count ; i++){
       [arrMutfetchImage addObject:arrayJson[i][@"folderName"]]
    }

    return arrMutfetchImage;
}

numberOfItemsInSection

return arrMutImages.count;

cellforrowatindexpath

imageView.image = [UIImage imageNamed: arrMutImages[indexPath.row]];

didSelectItemAtIndexPath

[arrMutImages removeAllObjects];
[arrMutImages addObject:arrayJson[indexPath.row][@"ImgList"]];
[collectionView reloadData];

如果有任何按钮从图像列表切换到文件夹,则在按钮操作中写入以下代码

[arrMutImages removeAllObjects];
[arrMutImages addObject:[self getFolderNames]];
[collectionView reloadData];

这就是我解决显示前两组图像的方法

我写了一个json文件,把他加入我的项目

{
    "Barvy": [ "Bila.jpg", "Cerna.jpg", "Cervena.jpg",
               "Fialova.jpg", "Hneda.jpg", "Modra.jpg",
               "Oranzova.jpg", "Zelena.jpg", "Zluta.jpg"],

    "Budovy": [ "Budova.jpg", "Cirkus.jpg", "Domov.jpg",
                "Dum.jpg", "Kostel.jpg", "Nemocnice.jpg",
                "Obchod.jpg", "Restaurace.jpg", "Skola.jpg"]
}

然后

    var arrImages = [String]()
    let dataUrl = Bundle.main.url(forResource: "test", withExtension: "json")


    override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.dataSource = self
    collectionView.delegate = self

    let jsonData = try! Data(contentsOf: dataUrl!)

    do {

        if let arrJson = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        as? Dictionary<String, AnyObject> {

            if let barvy = arrJson["Barvy"] as? [String] {
                arrImages = barvy
            }

            if let budovy = arrJson["Budovy"] as? [String] {
                arrImages += budovy
            }

        }
    } catch {
        print(error)
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell", for: indexPath) as? Cell {
        cell.imgView.image = UIImage(named: "\(arrImages[indexPath.row])")
        return cell
    }
    return UICollectionViewCell()
}

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

我的前 2 组图像终于显示在 collectionView 中了。 当我弄清楚如何首先仅显示类别名称并在单击后仅为单击的类别显示图像时,我将更新答案。