我正在尝试以编程方式创建一个包含六个单元格的Collection View。 Xcode 8中的iPhone模拟器告诉我,我的构建成功了。 但仍有错误。
非常感谢任何帮助发现导致我的细胞不在模拟器中显示的错误或错误。 (我将集合视图从对象库直接放入IB。此外,我希望每个单元格占据集合视图的整个大小,因此displayedCellDimensions
,因为当向前或向后时,用户将在单元格之间进行切换点击按钮。)谢谢!
import UIKit
class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//MARK: - Collection View Properties
@IBOutlet weak var ibCollectionView: UICollectionView!
var cellArray:[customCollectionViewCell] = Array(repeating: customCollectionViewCell(), count: 6)
let displayedCellDimensions = CGSize(width: 343, height: 248)
//MARK: - Xcode-generated Methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
ibCollectionView.dataSource = self
ibCollectionView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Collection View Methods
//Place cells in collection view and change the cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView.visibleCells.isEmpty {
for cell in 0...cellArray.count {
collectionView.addSubview(cellArray[cell])
return CGSize(width: 343, height: 248)
}
}
return CGSize(width: 343, height: 248)
}
//Register a new cell
func registerCell(_ collectionView: UICollectionView) {
for _ in 0...cellArray.count {
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellArray.count
}
...}
答案 0 :(得分:1)
在viewDidLoad()中尝试:
viewDidLoad() {
ibCollectionView.dataSource = self
ibCollectionView.delegate = self
}
将其添加到班级的顶部:
class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
您必须在ViewController类中使用这些函数:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {}