我正在开发一个模因生成器应用程序。模因生成器以模态方式呈现,并内置于标签栏 View Controller 中。第一个选项卡在表格 View 中显示所有已保存的模因,第二个选项卡旨在在 Collection View 中显示已保存的模因。模因生成器按照设计工作,并将生成的模因保存到位于 App Delegate 文件中的数组中(我知道这是有争议的,但这是练习的要求)。我正在尝试设置 Collection View ,但我无法在应用程序委托(delegate)文件中获取对 meme 对象的引用,我不明白为什么。
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var memes: [Meme]! {
didSet {
collectionView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return memes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.imageView.image = memes[indexPath].memedImage
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
我将此代码基于用于我的 TableView 的代码,它按设计工作。该代码是:
import UIKit
class TableViewMemesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var memes: [Meme]! {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return memes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let meme = memes[indexPath.row]
cell?.imageView?.image = meme.memedImage
cell?.textLabel?.text = meme.topText
return cell!
}
}
当用户保存新模因时,如何获取对数组数据的引用并将其显示在 Collection View 中? Here是 repo 协议(protocol)的链接。
最佳答案
你有一些问题,首先你必须创建一个自定义 CollectionViewCell:
class Cell: UICollectionViewCell {
@IBOutlet var imageView:UIImageView!
}
记得在 Storyboard中为 UICollectionViewCell 设置自定义类:
然后当您将单元格出列时,请确保 as!单元格
:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.imageView.image = memes[indexPath.row].memedImage
return cell
}
然后在你的 TabBarStoryboard.storyboard
中,你必须为你的 CollectionViewController
设置 delegate
和 datasource
(我检查过你的 github,你没有附加它们)。
最后的结果是:
关于ios - 无法在 Collection View 中显示存储在 App Delegate 中的数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045028/