【问题标题】:Set the size of UICollectionViewCell dynamically动态设置 UICollectionViewCell 的大小
【发布时间】:2017-06-13 09:07:53
【问题描述】:

我有一个 UICollectionViewCell,其中包含一个图像视图和一个标签。

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

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

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

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

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

我有一个显示内容的文本和图像数组。

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

【问题讨论】:

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


【解决方案1】:
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)
    }

【讨论】:

    【解决方案2】:

    标签的宽度 = 图像视图的宽度。 没关系。 对于高度,您可以使用 Intrinsic Content Size 函数来获取标签的大小。

    【讨论】:

      【解决方案3】:

      这里的collectioncell是Collection view的出口

       func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
      
              let cellsize = CGSize(width: (collectioncell.bounds.size.width/2) - 12, height:(collectioncell.bounds.size.height/3) - 20)
      
              return cellsize
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多