【发布时间】:2023-03-24 06:30:02
【问题描述】:
我正在尝试在表格视图单元格中实现集合视图。
我的表格视图单元格是 xib,我已将集合视图拖入其中。
然后,我为集合视图单元创建了一个类和 xib:
class MyCollectionViewCell: UICollectionViewCell {
var media: Image?
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func initialize(media: PostImage) {
self.media = media
if let url = media.url {
imageView.kf.setImage(with: URL(string: url))
}
}
}
我已经为 xib 指定了“MyCollectionViewCell”类,并为它指定了标识符“MyCollectionViewCell”。
然后,在我的表格视图单元格类中,我做了以下操作:
class MyTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var post: Post!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var mediaCollectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
mediaCollectionView.delegate = self
mediaCollectionView.dataSource = self
let mediaCollectionViewCell = UINib(nibName: "MyCollectionViewCell", bundle: nil)
mediaCollectionView.register(mediaCollectionViewCell, forCellWithReuseIdentifier: "MyCollectionViewCell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath as IndexPath) as? MyCollectionViewCell else {
fatalError("The dequeued cell is not an instance of MyCollectionViewCell.")
}
let media = post.images[indexPath.row]
cell.initialize(media: media)
return cell
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func initialize(post: Post) {
self.post = post
title.text = post.title
self.mediaCollectionView.reloadData()
}
}
问题是,当我运行它时,集合视图永远不会显示。标题标签文字显示正常,但集合视图不显示,不知道自己做错了什么。
cellForItemAt 似乎没有被调用,因为当我在函数顶部添加print("hello") 时,它永远不会出现在控制台中。
我做错了什么?
【问题讨论】:
标签: ios swift uitableview uicollectionview