ios - UICollectionViewController - 展开可选值时意外发现 nil

标签 ios swift

我正在尝试实现一个 Collection View Controller ,但严重失败...我如何摆脱这个展开错误?当我在 cellForRowAtIndexPath 函数中创建 collectionView 单元格时,会发生这种情况。

这是代码。

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = picturesCollectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellIdentifier, forIndexPath: indexPath) as? PhotoBrowserCollectionViewCell

    if let photoObject = pictureObjects.objectAtIndex(indexPath.row) as? PictureElement {

        let title = photoObject.title ?? "" // if photoObject.title == nil, then we return an empty string

        let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(photoObject.timeStamp))
        let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject)

        let author = photoObject.author ?? ""

        let issueNumber = photoObject.issueNumber ?? ""
        let volumeNumber = photoObject.volumeNumber ?? ""

        let nodeID = photoObject.nodeID ?? 0

        let imageURL = photoObject.imageURL ?? ""

        cell!.request?.cancel()

        // Using image cache system to make sure the table view works even when rapidly scrolling down the screen.
        if let image = self.imageCache.objectForKey(imageURL) as? UIImage {

            cell!.imageView.image = image

        } else {

            cell!.imageView.image = nil
            cell!.request = Alamofire.request(.GET, imageURL).responseImage { response in
                if let image = response.result.value {
                    self.imageCache.setObject(response.result.value!, forKey: imageURL)
                    cell!.imageView.image = image

                } else {
                }
            }
        }
    } else {
}
    return cell!

}

此外,我已经尝试使用guard-let 语句,但它不起作用。这是:

        guard let cell = picturesCollectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellIdentifier, forIndexPath: indexPath) as? PhotoBrowserCollectionViewCell else {

        print("cell could not be initialized as PhotoBrowserCollectionViewCell, hence it will be casted to another default UICollectionViewCell type")
        return collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellIdentifier, forIndexPath: indexPath)


    }

最佳答案

假设您正在使用 Storyboard...

  1. 确保为 Storyboard 中的单元设置重用标识符,以匹配 PhotoBrowserCellIdentifier 的值。

  2. 确保将 Storyboard 中的单元格的类设置为 PhotoBrowserCollectionViewCell。

关于ios - UICollectionViewController - 展开可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33159839/

相关文章:

ios - Alamofire 监控网络状态

ios - executeFetchRequest 包含 "<null>"和我的数据

swift - Swift 中函数重载参数的优先级

ios - UICollectionView 的 UILabel 中的奇怪文本问题

Swift - 从 CollectionView 中的相册中获取照片并保持分辨率

ios - CGContextClipToMask 不剪辑

ios - UILabel 的约束不起作用

iphone - XCode 4.2 自定义模板创建?

ios - JSON 解码器类型不匹配错误

ios - 为什么我无法保存应用内购买?