【问题标题】:Collection View inside Table View Cell not being called表视图单元格内的集合视图未被调用
【发布时间】: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


    【解决方案1】:

    我认为问题在于集合视图的高度非常小,以至于没有显示出来。 尝试设置表格视图单元格的高度:

    func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
         return 100
    }
    

    100 应该大于集合视图

    【讨论】:

    • 表格视图和表格视图单元格正在显示。不是集合视图和单元格。
    • @user6724161 你找到解决办法了吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    相关资源
    最近更新 更多