本文介绍了在隐式展开可选值 (UICollectionView) 时意外发现 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想制作在获取新项目后重新加载其数据的集合视图.但是当我尝试重新加载集合视图时,我收到此错误
I want to make collection view that reloads its data after getting new items. But when im trying to reload collection view im getting this error
这是视图控制器的代码
import UIKit
class GalleryViewController: UIViewController {
var presenter : ViewToPresenterPhotoProtocol?
@IBOutlet var collectionView: UICollectionView!
let reuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
presenter?.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension GalleryViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.presenter?.photos?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoCollectionViewCell
cell.label.text = self.presenter?.photos?[indexPath.item].name
cell.backgroundColor = UIColor.yellow
return cell
}
// MARK: - UICollectionViewDelegate protocol
private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
extension GalleryViewController: PresenterToViewPhotoProtocol{
func onFetchPhotoSuccess() {
self.collectionView.reloadData()
}
func onFetchPhotoFailure(error: String) {
print("View receives the response from Presenter with error: \(error)")
}
}
我不知道如何在故事板的集合视图中正确地重新加载数据,所以如果你能帮我解决这个问题,我将非常感激
I don't know how to properly reload data in storyboard's collection view so I'll be pretty thankful if you'll help me solving this issue
推荐答案
也许你的 GalleryViewController
是在没有 xib/storyboard 的情况下初始化的.
Maybe your GalleryViewController
was initialized without xib/storyboard.
如果您使用故事板,请尝试以下操作:
If you're using storyboard try this:
let storyboard = UIStoryboard(name: 'yourStoryboardName', bundle: .main)
let controller = storyboard.instantiateViewController(identifier: "yourControllerIdentifier") as! GalleryViewController
如果您使用的是 xib 试试这个:
If you're using xib try this:
let controller = UIViewController(nibName: "yourControllerNibName", bundle: .main) as! GalleryViewController
这篇关于在隐式展开可选值 (UICollectionView) 时意外发现 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!