如何在 Swift 中的 Collection View 上显示图像数组

Posted

技术标签:

【中文标题】如何在 Swift 中的 Collection View 上显示图像数组【英文标题】:How to display array of images on Collection View in Swift 【发布时间】:2017-08-02 05:19:18 【问题描述】:
func numberOfSections(in collectionView: UICollectionView) -> Int 
    return 1


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
     print("gallery count : \(self.arrayGallerySingle.count)")
    return self.arrayGallerySingle.count


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gallerycell", for: indexPath) as! GalleryViewCell
return cell


//API Fetching method
func galleryFetch()

    let prs = [
        "id": dealIDGallery,
        "deal_single_page": "1" as String
    ]

    Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion:  result in
        let jsonResponseSingle = result as? NSDictionary
        print(" jsonResponse\(String(describing: jsonResponseSingle))")

        if let resultGallery = jsonResponseSingle?.value(forKey: "result") as? NSArray

            for keyValuesGallery in resultGallery 

                let gallerySingle = (keyValuesGallery as AnyObject).value(forKey: "gallery_images") as? NSArray

                print("Gallery Images Key: \(gallerySingle)")
                self.arrayGallerySingle = gallerySingle as! [AnyObject]

                DispatchQueue.main.async  () -> Void in
                    self.collectionView?.reloadData()

                
            

        
    )

如何在 UICollectionViewCell 上显示带有键 gallery_images 的图像数组?这条线 print("Gallery Images Key: \(gallerySingle)") 在控制台上打印所需的图像数组,但我无法在 collectionView 上显示。我的JSON 回复是http://www.jsoneditoronline.org/?id=8eccb63976d76be7d0b2d1b0e8f02306。我也在我的项目中使用SDWebImage。我已经检查了datasource 连接和collectionView IBoutlet 以及单元格内的图像。我是 Swift 的初学者,请帮助,如果需要任何进一步的信息,请询问

【问题讨论】:

【参考方案1】:

Swift 3.0这是我更新的答案希望它也能帮助别人

func numberOfSections(in collectionView: UICollectionView) -> Int 
    return 1


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
     print("gallery count : \(self.arrayGallerySingle.count)")
    return self.arrayGallerySingle.count



func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gallerycell", for: indexPath) as! GalleryViewCell
   if let imgUrl = arrayGallerySingle[indexPath.row] as? String 
        if let url = NSURL(string: imgUrl) 
            cell.galleryImage?.sd_setImage(with: url as URL, placeholderImage: UIImage(named: "place holder image"), options: .lowPriority)
        
        else
            let alertController = UIAlertController(title: "No Gallery Images", message: "test", preferredStyle: .alert)
            let okButton = UIAlertAction(title: "Okay", style: .default, handler: nil)
            alertController.addAction(okButton)
            alertController.present(alertController, animated: true, completion: nil)
        
    
return cell


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets 
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat 
    return 0.0


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat 
    return 0.0


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize

    return CGSize(width: collectionView.frame.size.width/2, height: collectionView.frame.size.height/3)



func galleryFetch()

    let prs = [
        "id": dealIDGallery,
        "deal_single_page": "1" as String
    ]

    Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion:  result in
        let jsonResponseSingle = result as? NSDictionary
        print(" jsonResponse\(String(describing: jsonResponseSingle))")

        if let resultGallery = jsonResponseSingle?.value(forKey: "result") as? NSArray

            for keyValuesGallery in resultGallery 

                let gallerySingle = (keyValuesGallery as AnyObject).value(forKey: "gallery_images") as? NSArray

                print("Gallery Images Key: \(gallerySingle)")
                self.arrayGallerySingle = gallerySingle as! [AnyObject]

                if self.arrayGallerySingle.count > 0 

                    DispatchQueue.main.async  () -> Void in
                        self.collectionView?.reloadData()

                    
                 else 
                    let alertController = UIAlertController(title: "Message", message: "No images found.", preferredStyle: .alert)
                    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: self.doSomething))
                    self.present(alertController, animated: true, completion: nil)
                
            
        
    )

【讨论】:

【参考方案2】:

Swift 3.0

您可以使用 SDWebcache 实现这种方式以在 collectionView 单元格图像中加载图像。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gallerycell", for: indexPath) as! GalleryViewCell

            if let imgUrl = arrayGallerySingle[indexPath.row] as? String 
                if let url = URL(string: imgUrl) 
                   //Replace with your imageView outlet
                    cell.imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "place holder image"), options: .lowPriority)
                
            
            return cell
        

如果要在 collectionView 中显示 6 个单元格,则必须将 UICollectionViewLayout 方法设置为定义的单元格大小,如下所示。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    
    return CGSize(width: collectionView.frame.size.width/2, height: collectionView.frame.size.height/3)


您可以在数组计数不为空时显示警报以及为什么在 for 循环中重新加载 Collection 视图,如下所示实现它。

Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion:  result in
            let jsonResponseSingle = result as? NSDictionary
            print(" jsonResponse\(String(describing: jsonResponseSingle))")

            if let resultGallery = jsonResponseSingle?.value(forKey: "result") as? NSArray

                for keyValuesGallery in resultGallery 

                    let gallerySingle = (keyValuesGallery as AnyObject).value(forKey: "gallery_images") as? NSArray

                    print("Gallery Images Key: \(gallerySingle)")
                    self.arrayGallerySingle = gallerySingle as! [AnyObject]
                

                if self.arrayGallerySingle.count > 0 

                    DispatchQueue.main.async  () -> Void in
                        self.collectionView?.reloadData()

                    

                 else 
                    let alertController = UIAlertController(title: "Your Title", message: "their is no images", preferredStyle: .alert)
                    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                    self.present(alertController, animated: tru, completion: nil)
                

            
        )

【讨论】:

它解决了我的问题,我想在集合视图中一次显示 6 张图像,没有单元格间距@Jaydeep 我也想显示警报我没有图像是他们的@Jaydeep 如果他们没有图片,我想显示警报@Jaydeep @Sunny,检查更新的答案。显示警报很简单,只需要检查图像数组计数。 检查@Jaydeep

以上是关于如何在 Swift 中的 Collection View 上显示图像数组的主要内容,如果未能解决你的问题,请参考以下文章

Xcode Swift Collection View:每当点击按钮时,如何在部分中添加项目数?

在 iOS Swift 中,在 Swift 4 中的 TableView 中为 CollectionView 集成不同的数组

swift collection view:如何更改一个特定单元格的图像视图颜色?

如何在 Collection 视图中为每个单元格添加 edgeInsets -Swift

使用 Swift 语言编写递归函数以遍历 Objective C 中的 Collection 对象

Swift + Realm:如何从 collection.find 的范围内更改外部变量