我正在尝试以编程方式创建一个包含六个单元格的 Collection View 。 Xcode 8 中的 iPhone 模拟器告诉我构建成功。 还是有错误。
对于发现导致我的单元格无法在模拟器中显示的一个或多个错误的任何帮助,我们将不胜感激。 (我将 Collection View 从 Object Library 直接放入 IB。此外,我希望每个单元格都占据 Collection View 的整个大小,因此 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
}
...}
最佳答案
在你的 viewDidLoad() 中尝试:
viewDidLoad() {
ibCollectionView.dataSource = self
ibCollectionView.delegate = self
}
将此添加到您类(class)的顶部:
class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
您必须在 ViewController 类中使用这些函数:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {}
关于swift - 为什么我的 Collection View Cells 不显示在 iPhone 模拟器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463354/