gpt4 book ai didi

swift - 向 UICollectionView 添加单元格时出现问题

转载 作者:行者123 更新时间:2023-11-30 12:24:09 24 4
gpt4 key购买 nike

尝试向我的 ViewController 添加一个单元格,但遇到了麻烦。我想知道我是否已经召集了所有代表。目前,我可以更改 Collection View 背景的颜色,但无法添加任何单元格。

我正在使用 Listing() 对象中的文本数组来驱动 Collection View 单元格。在 viewDidLoad 上,长度为 4。我设想将此计数用于 numberofItemsInSection,但是,如果我将 print 语句放在那里,则它永远不会被打印。这让我认为调用了错误的委托(delegate)并且该方法永远不会被命中。对吗?

import UIKit 

class ListingDetailViewController: UIViewController,
UICollectionViewDelegateFlowLayout {
var listing = Listing()
// @IBOutlet var image: UIImageView!
@IBOutlet var post: UITextView!
@IBOutlet var price: UILabel!
@IBOutlet var amenitiesCollection: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationItem.title = listing.title
self.amenitiesCollection!.backgroundColor = UIColor.gray
print(listing.amenities.count)//printed 4

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
print(listing.amenities.count)
return listing.amenities.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier = "UICollectionViewCell"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
return cell
}
}

最佳答案

确保您已将 CollectionView 委托(delegate)和数据源链接到 View Controller 。

viewDidLoad()中添加:

    self.amenitiesCollection.delegate = self
self.amenitiesCollection.dataSource = self

====================================

编辑:

如果您已经链接了委托(delegate)和数据源,请尝试在 viewDidAppear(_:) 中重新加载 Collection View

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.amenitiesCollection.reloadData()
}

关于swift - 向 UICollectionView 添加单元格时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415258/

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