【问题标题】:How to make dynamic height for UICollectionViewCell with dynamic type and fixed width?如何为具有动态类型和固定宽度的 UICollectionViewCell 制作动态高度?
【发布时间】:2021-10-19 22:28:21
【问题描述】:

我正在做一个项目,我们使用 UICollectionViewcustom 单元格。单元格看起来像this。我的所有元素都包含在 UIView 中。 当然,文字要短得多。 无论如何,我在 sizeForItemAt 函数中决定 CollectionView 的宽度:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width - 50, height: (collectionView.frame.width * 0.7))
}

我需要找到一种方法来保持此固定宽度,但在启用动态类型时使单元格的高度可调整大小。单元格底部的标签必须能够增大大小,因此可以根据需要调整底部单元格的大小,而不会影响 ImageView 在顶部的大小。然而,这似乎比看起来更难,因为我的 ImageView 的大小为 0.7 * 我的 CollectionView 的宽度(因此它在任何屏幕上都有适当的高度)。

我的标签包含在 VerticalStackView 中,而我的 VerticalStackView 和“1”标签包含在 Horizo​​ntalStackView 中。 我曾尝试在示例项目中的这种视图层次结构上使用动态类型,并且视图会在不影响 ImageView 的情况下增加高度,但我似乎无法在 CollectionViewCell 中做同样的事情。

我尝试使用为我的 CollectionViewCell 启用自动大小的自动布局,但这只会破坏我的宽度和高度,并且还会剪裁我再也看不到它们的标签。

希望你能帮帮我!

非常感谢。

【问题讨论】:

    标签: ios uicollectionview uikit dynamic-type-feature


    【解决方案1】:

    您可以使用以下文字找到标签的高度:

    extension String {
        func height(withWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = self.boundingRect(
                with: constraintRect,
                options: .usesLineFragmentOrigin,
                attributes: [NSAttributedString.Key.font: font],
                context: nil)
            return ceil(boundingBox.height)
        }
    }
    

    将您的集合视图的 sizeForItemAt 修改为:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width - 50.0
        let labelHeight = "your text".height(withWidth: width, font: .systemFont(ofSize: 17.0))
        let imageHeight = width * 0.7
        return CGSize(width: width, height: labelHeight+imageHeight)   
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多