【问题标题】:How to add images to collectionview from folder in project?如何从项目中的文件夹将图像添加到collectionview?
【发布时间】:2017-05-02 02:58:54
【问题描述】:

我想问有没有办法从文件夹解析图像到数组。

我有类别:“颜色”、“建筑物”等,每个类别文件夹中都有相关的图像。

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

【问题讨论】:

    标签: ios swift image uicollectionview load


    【解决方案1】:

    您的图像在捆绑文件中,因此您可以直接使用带有图像名称的图像,例如[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"];
      }
    }
    

    在collectionview 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

    如何在 UIOLLECTIONVIEW 中显示图像

    先写这个

    @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];
    

    【讨论】:

    • 非常感谢!!!我刚刚为每个组获得了一个 XML 文件。有没有办法使用这些 XMLs 而不是 JSON?或者我可以使用一些从 XML 到 JSON 的在线转换器
    • 我添加了我如何解决它的答案,但是如果你能帮助解决“如何首先只显示类别的名称,然后点击后只显示点击的类别的图像。”随时回答:) @Tinu Dahiya
    • @deniskakacka 检查我的新更新答案。我现在没有 xcode 或 mac,所以我只是在记事本中编写这段代码并在这里发布。我尽力而为,完整的解决方案几乎就在这里。所以检查你得到的输出是什么,如果不正确,请告诉我。
    【解决方案2】:

    首先按升序重命名所有组的图像以及组名,如“Barvy_0.jpg”等..

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

    var image_name:String = ""
    

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

    image_name = "Barvy"
    

    在集合视图中:

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

    【讨论】:

    • 是的,但是在每个文件夹中都有很多其他图像,我无法全部重命名.. 还有其他方法吗?
    • 那么你应该为每个文件夹的图像制作数组
    【解决方案3】:

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

    我写了一个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 中。 当我弄清楚如何首先仅显示类别名称并单击后仅显示单击类别的图像时,我将更新答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 2022-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      相关资源
      最近更新 更多