ios - 动态设置 UICollectionViewCell 的大小

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我有一个 UICollectionViewCell,它包含一个 ImageView 和一个标签。

只有当我有 ImageView 时,我才能动态调整单元格的大小。

我在带有自动布局的 imageView 下方添加了一个标签。

在 viewDidLoad 上,图像被截断或文本被截断。如何在 UICollectionViewCell 中动态调整 ImageView 和标签的大小。

以下是我的代码,仅适用于 imageView

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        let imageSize = model.images[indexPath.row].size
        return imageSize
    }

我在显示内容的位置有一组文本和图像。

任何帮助将不胜感激。谢谢。

最佳答案

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        let imageSize = model.images[indexPath.row].size

        //find the height of label on setting text.
        //create a temp label
                let tempLabel = UILabel()
        tempLabel.numberOfLines = 0
        tempLabel.text = "abcd" //set ur cells text here
        let labelSize = tempLabel.intrinsicContentSize

        return CGSize(width: imageSize.width + labelSize.width, height: imageSize.height + labelSize.height)
    }

关于ios - 动态设置 UICollectionViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517014/

相关文章:

ios - 寄存器有什么问题(_ :forCellWithReuseIdentifier:) on UICollectionView?

ios - 无法执行单击导航栏自定义按钮

ios - 角标(Badge)从未清除

ios - SwiftUI 工作表 : Inconsistent sheet behaviour with navigationBarItems

ios - UICollectionView 委托(delegate)中的搜索栏 subview

ios - CollectionView + UIKit Dynamics 在 performBatchUpdates 上崩溃 :

ios - 如何在框架中的 Objective-C 文件中使用 Swift 类?

ios - 当文本字段在 uitableview 的单元格中时,不调用 touchesBegan

ios - Firestore 安全规则在模拟器中有效,但在应用程序中失败

Swift,如何将数据读回结构体?