ios - 使用数据将 PFFile 转换为 UIImage 并附加到数组

标签 ios swift uiimageview uiimage pffile

我可以在该站点上看到几个类似的线程,但是没有一个阐明如何从数组中取回数据。

我正在尝试从服务器上获取一个 PFFile 并将其设置为 Collection View 中的图像

for object in packs {

      self.packName.append(object["packName"] as! String)
      self.packDescription.append(object["packDesctription"] as! String)

       var objectImage = object["file"] as! PFFile
       objectImage.getDataInBackground(block: { (imageData, error) in

        if error == nil {
           var myImage = UIImage(data: imageData!)
           self.packImage.append(myImage!)
        }
        })

  }

打印 packImage 显示一堆数据:所以里面有东西..

[<UIImage: 0x608000287210>, {259, 194}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}, <UIImage: 0x600000286cc0>, {259, 194}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}, <UIImage: 0x600000286cc0>, {259, 194}, <UIImage: 0x608000287800>, {189, 267}]
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}, <UIImage: 0x600000286cc0>, {259, 194}, <UIImage: 0x608000287800>, {189, 267}, <UIImage: 0x600000287620>, {259, 194}]

但是,当我尝试将图像进一步向下设置时,出现错误索引超出范围。

cell.imageCell.image = packImage[indexPath.row]

------------编辑随附的 UICollectionViewDelegate 的完整代码----------------

import UIKit
import Parse

private let reuseIdentifier = "Cell"

class PackViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate  {

    //have to drag in outlet because not in CVC anymore
    @IBOutlet var collectionView: UICollectionView!

    //var delegate: PackViewDelegate?

    var packName = [""]  // the total packs in the app
    var packDescription = [""]
    var packTitle = [""]
    var packImage = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()


        let packQuery = PFQuery(className: "Pack")

        packQuery.findObjectsInBackground(block: { (objectsArray, error) in
            if error != nil {
                print(error!)
            } else if let packs = objectsArray {

                self.packName.removeAll() // remove the empty strings
                //self.packImage.removeAll()
                self.packDescription.removeAll()

                for object in packs {

                    self.packName.append(object["packName"] as! String)
                    self.packDescription.append(object["packDesctription"] as! String)

                    // get the PFFile from the server
                    var objectImage = object["file"] as! PFFile
                    objectImage.getDataInBackground(block: { (imageData, error) in

                        if error == nil {
                            //convert the data to an image and append it to array
                            var myImage = UIImage(data: imageData!)
                            self.packImage.append(myImage!)
                            print(self.packImage)
                        }
                    })

                }

                //only works when create iboutlet of collection view because in VC not CVC
                self.collectionView?.reloadData()

            }
        })

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }


    // MARK: UICollectionViewDataSource

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


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


    func UIColorFromHEX(hexValue: UInt) -> UIColor {
        return UIColor(
            red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(hexValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PackCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PackCollectionViewCell


        cell.labelCell.text = packDescription[indexPath.row]

//////-------------------------------------------------------------- this is where it crashes
        cell.imageCell.image = packImage[indexPath.row]



        cell.imageCell.layer.masksToBounds = true
        cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height/2

        cell.imageCell.layer.borderWidth = 3
        cell.imageCell.layer.borderColor = UIColorFromHEX(hexValue: 0x62aca2).cgColor

        return cell

    }


    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            // handle the segue to JourneyViewController with variable "selectedPack"
            // not sure why you need to set the storyboard but it works
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
            //create instance of the viewcontroller
        let transportJourneyViewController = storyBoard.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
            //value to pass - has been defined in journey
        transportJourneyViewController.selectedPack = packName[indexPath.row]
            //present the vc
        self.present(transportJourneyViewController, animated:true, completion:nil)

    }


    @IBAction func logoutButtonTapped(_ sender: Any) {
        PFUser.logOut()
        if (PFUser.current() == nil) {
            performSegue(withIdentifier: "segueLogout", sender: self)
        } else {
            MyFunctions.createAlert(errorTitle: "Oops...", errorMessage: "Something happened when logging you out.", className: self)
        }
    }

} // class

enter image description here

最佳答案

我认为您的数组 有问题。你的

packName.count > self.packImage.count

numberOfItemsInSectionto 方法中使用这个数组 self.packImage 来消除崩溃

试试这个

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

希望对你有帮助

关于ios - 使用数据将 PFFile 转换为 UIImage 并附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41276415/

相关文章:

ios - 在另一个项目中使用一个项目的应用程序委托(delegate)/ View Controller

ios - 将数据从 TableView 传递到 View Controller

swift - Storyboard的 View Controller 之间共享变量?

ios - 快速返回上一个 segue 而不会丢失标签栏 Controller

ios - 为什么 return 语句不会停止程序?

ios - 我怎样才能看到 UIImageView 中的图像?

iphone - 色度计 RGB iPhone ios 代码

ios - 我们可以使用 IOS Enterprise 帐户进行测试,然后使用 IOS Developer 帐户进行最终测试并上传到应用商店吗?

ios - 如何为 UITextFields 中的左 View 图像添加 X px 的填充?

ios - 意外发现 nil UIImageView