尝试将一个单元格添加到我的ViewController中,我遇到了麻烦。我想知道我是否有我的所有代表。目前,我可以更改集合视图的背景颜色,但无法添加任何单元格。
我使用了我的Listing()对象中的一组文本来驱动集合视图单元格。在viewDidLoad上,长度为4.我设想将此计数用于numberofItemsInSection,但是,如果我将print语句放在那里,则永远不会打印。这让我觉得调用了错误的委托,方法永远不会被击中。正确的吗?
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
}
}
答案 0 :(得分:0)
确保已将CollectionView委托和数据源链接到视图控制器。
在viewDidLoad()
添加:
self.amenitiesCollection.delegate = self
self.amenitiesCollection.dataSource = self
==================================
修改强>
如果您已经链接了委托和dataSource,请尝试重新加载viewDidAppear(_:)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.amenitiesCollection.reloadData()
}