gpt4 book ai didi

ios - 用图像填充 UICollectionView 返回 nil : Swift 2

转载 作者:搜寻专家 更新时间:2023-11-01 06:43:51 25 4
gpt4 key购买 nike

我有一个 UICollectionView,其中有一个带有 UIImageView 的自定义单元格,还有一个带有 socket 的自定义类

class theCell: UICollectionViewCell { 
@IBOutlet var theImage:UIImageView!
}

我有一组 UIImage(它只有一个常量图像)。该图像位于主包中。

var tempImages = [UIImage(named: "placeholder.png" )]

委托(delegate)方法

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tempImages.count
}

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

let cell = self.collectionView?.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! theCell

//Unexpectadly found nil
cell.theImage.image = tempImages[indexPath.row]
return cell
}

最佳答案

如果你添加了这一行:

self.collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "cell")

然后先删除它,这里是完整的工作代码:

CollectionViewController.swift

import UIKit

class CollectionViewController: UICollectionViewController {

var tempImages = [UIImage]()

override func viewDidLoad() {
super.viewDidLoad()
tempImages.append(UIImage(named: "bg.jpg")!)
}

// MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}


override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return tempImages.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell

// Configure the cell
cell.theImage.image = tempImages[indexPath.row]
println(cell.theImage.image)
return cell
}
}

CollectionViewCell.swift

import UIKit

class CollectionViewCell: UICollectionViewCell {


@IBOutlet var theImage:UIImageView!

}

并且不要忘记为您的单元分配标识符:

enter image description here

Sample了解更多信息。

关于ios - 用图像填充 UICollectionView 返回 nil : Swift 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com