尝试将Image从从Firebase加载的UICollectionView传递到另一个VC

时间:2018-05-31 22:48:30

标签: ios swift uicollectionview uiimageview

我遇到的问题是将图像从我的MainDetailVC设置为在我的主视图控制器中选择的单元格中的图像。我一直为desVC.detailImage.image获得零值。如果有人有任何提示,那将是非常棒的。

对于斯威夫特来说还是一个新手,所以请原谅我的任何无知。洛尔

谢谢!

import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ImageCellDelegate {




@IBOutlet weak var popImageCollection: UICollectionView!
@IBOutlet weak var imageCollection: UICollectionView!


var customImageFlowLayout = CustomImageFlowLayout()
var popImageFlowLayout = PopImagesFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var homePageTextArray = [NewsTextModel]()

var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()
    dbRef = Database.database().reference().child("images")
    dbPopularRef = Database.database().reference().child("popular")
    loadDB()
    loadImages()
    loadText()
    customImageFlowLayout = CustomImageFlowLayout()
    popImageFlowLayout = PopImagesFlowLayout()

    imageCollection.backgroundColor = .clear
    popImageCollection.backgroundColor = .white


    // Do any additional setup after loading the view, typically from a nib.
}
func loadText() {
    dbRef.queryOrdered(byChild: "order").observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            self.homePageTextArray.removeAll()
            for homeText in snapshot.children.allObjects as! [DataSnapshot] {
                let homeTextObject = homeText.value as? [String: AnyObject]
                let titleHome = homeTextObject?["title"]
                let categoryButtonText = homeTextObject?["category"]
                self.imageCollection.reloadData()
                let homeLabels = NewsTextModel(title: titleHome as! String?, buttonText: categoryButtonText as! String?)
                self.homePageTextArray.append(homeLabels)
            }
        }
    })
}
func loadImages() {
    popImageArray.append(UIImage(named: "2")!)
    popImageArray.append(UIImage(named: "3")!)
    popImageArray.append(UIImage(named: "4")!)

    self.popImageCollection.reloadData()
}
func loadDB() {
    dbRef.queryOrdered(byChild: "order").observe(DataEventType.value, with: { (snapshot) in
        var newImages = [BlogInsta]()
        for BlogInstaSnapshot in snapshot.children {
            let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
            newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.imageCollection {
       return images.count
    } else {
        return popImageArray.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.imageCollection {
   let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
        cell.delegate = self
        cell.contentView.backgroundColor = UIColor.clear
    let image = images[indexPath.row]
        let text: NewsTextModel
        text = homePageTextArray[indexPath.row]
        cell.categoryButton.setTitle(text.buttonText, for: .normal)
        cell.newTitleLabel.text = text.title
    cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
        return cell
    } else {
       let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
        let popPhotos = popImageArray[indexPath.row]
        cellB.popularImageView.image = popPhotos
        cellB.popularImageView.frame.size.width = view.frame.size.width
            return cellB
    }

}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let desVC = mainStoryboard.instantiateViewController(withIdentifier: "MainDetailViewController") as! MainDetailViewController
    let imageIndex = images[indexPath.row]

    let imageURLString = imageIndex.url
    print(imageURLString)
    let imageUrl:URL = URL(string: imageURLString)!
    let imageData: NSData = NSData(contentsOf: imageUrl)!
    let image = UIImage(data: imageData as Data)
    desVC.detailImage.image = image
    performSegue(withIdentifier: "toDetails", sender: self)

}


func MusicWasPressed() {
    performSegue(withIdentifier: "homeToMusic", sender: self)
}

func SneakersWasPressed() {
    performSegue(withIdentifier: "homeToSneakers", sender: self)
}

func RandomWasPressed() {
    performSegue(withIdentifier: "homeToRandom", sender: self)
}

func FashionWasPressed() {
    performSegue(withIdentifier: "homeToFashion", sender: self)
}
func EntertainmentWasPressed() {
    performSegue(withIdentifier: "homeToEntertainment", sender: self)
}


}

1 个答案:

答案 0 :(得分:1)

问题是你不能在这里传递

 performSegue(withIdentifier: "toDetails", sender: self)

你创建一个desVC没有推,并使用segue,也不要做

let imageData: NSData = NSData(contentsOf: imageUrl)!

因为它会阻止主线程我建议发送图片的网址并加载到那里说SDWebImage

//

首先澄清你有2个选项首先是你创建一个desVC,然后使用已发送的参数启动它然后推送到self.navigationController 使用segue当你使用segues并想要将数据发送到目标实现prepare(for segue,因此重构为

1 -

 performSegue(withIdentifier: "toDetails", sender: imageURLString )

2 -

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toDetails" { 
       let nextScene = segue.destination as? MainDetailViewController {
          nextScene.imageURLString = sennder as! String
          nextScene.sendedTitle = self.sendedTitle
       } 

    }
}

3-在呈现destinationVC之前不要访问UI元素