尝试将图像从从 Firebase 加载的 UICollectionView 传递到另一个 VC
Trying to pass Image from UICollectionView loaded from Firebase, to another VC
我遇到的问题是将 MainDetailVC 中的图像设置为在主视图控制器中选择的单元格中的图像。我一直得到 desVC.detailImage.image
的零值。如果有人有任何提示,那就太棒了。
swift 还是很新,所以请原谅我的无知。哈哈
谢谢!
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)
}
}
问题是你这里没有传
performSegue(withIdentifier: "toDetails", sender: self)
你创建了一个没有推送的desVC
,并使用了一个segue,也不要这样做
let imageData: NSData = NSData(contentsOf: imageUrl)!
因为它会阻塞主线程,所以我建议发送图像的 url 并将其加载到 SDWebImage
//
首先要澄清你有两个选择,首先是像你一样创建一个 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- 在目标 VC 出现之前不要访问 UI 元素
我遇到的问题是将 MainDetailVC 中的图像设置为在主视图控制器中选择的单元格中的图像。我一直得到 desVC.detailImage.image
的零值。如果有人有任何提示,那就太棒了。
swift 还是很新,所以请原谅我的无知。哈哈
谢谢!
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)
}
}
问题是你这里没有传
performSegue(withIdentifier: "toDetails", sender: self)
你创建了一个没有推送的desVC
,并使用了一个segue,也不要这样做
let imageData: NSData = NSData(contentsOf: imageUrl)!
因为它会阻塞主线程,所以我建议发送图像的 url 并将其加载到 SDWebImage
//
首先要澄清你有两个选择,首先是像你一样创建一个 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- 在目标 VC 出现之前不要访问 UI 元素