我不知道处理CollectionView的代码有什么问题。编译器显示一个错误,指出以NSException类型的未捕获异常终止。另一个TableViewController与相同的数据模型一起工作正常。当我单击集合视图的选项卡栏时,它会抛出错误。
import Foundation
import UIKit
class MemeCollectionViewController: UICollectionViewController {
var memes: [Meme]!
@IBOutlet var memeCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
createRightBarButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
memeCollectionView.reloadData()
}
func createRightBarButtonItem() {
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "+",
style: .plain,
target: self,
action: #selector(goToViewController))
}
func goToViewController(){
let createMemeViewController = self.storyboard!.instantiateViewController(withIdentifier: "CreateMemeViewController") as! CreateMemeViewController
present(createMemeViewController, animated: true, completion: nil)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return memes.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MemeCollectionViewCell", for: indexPath) as! MemeCollectionViewCell
let meme = self.memes[(indexPath as NSIndexPath).row]
cell.memeCollectionImageView?.image = meme.memedImage
return cell
}
}