【问题标题】:UICollectionView dynamic header size calculationUICollectionView 动态表头大小计算
【发布时间】:2018-12-11 09:25:54
【问题描述】:

我知道已经有很多关于这个主题的帖子,但他们不知何故没有引导我找到解决方案,在这一点上,经过几天的尝试,我不知道该怎么办。

所以我有一个UICollectionView,我有一个标题。对于标题,我创建了自己的UICollectionReusableView。它包含一个 StackView,其中有两个标签。它们都具有动态大小(Lines = 0)。这些是 StackView 的约束(我也尝试将底部约束设置为 = 0):

StackView 约束

我这样计算标题大小...

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    let item = displayItems.object(at: UInt(section)) as! MySectionDisplayItem

    let reusableView: MyReusableView = UIView.fromNib()
    reusableView.setTitle(text: item.getTitle())
        .setSubtitle(subtitle: item.getSubtitle())

    return reusableView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
}

...并返回要显示的视图:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let item = displayItems.object(at: UInt(indexPath.section)) as! MySectionDisplayItem

    let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "myReusableView", for: indexPath) as! MyReusableView

    reusableView.setTitle(text: item.getTitle())
        .setSubtitle(subtitle: item.getSubtitle())

    return reusableView
}

在我的UICollectionReusableViewUICollectionView 中启用了自动布局。

我尝试过的一些事情:

  • 在我的标签上将preferredMaxLayoutWidth 设置为不同的正值
  • 在单独的视图中嵌入标签
  • 使用约束而不是使用 StackView

我希望我没有混淆我找到的一些解决方案,但无论如何我认为这样一个“简单”的事情并不难实现。

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    我终于通过限制宽度解决了这个问题:

    reusableView.translatesAutoresizingMaskIntoConstraints = true
    reusableView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
    

    可能您还必须解决内容压缩阻力。

    【讨论】:

    • @AakashDave 在我的 CollectionView 的 referenceSizeForHeaderInSection 方法中
    • 嗨。你解决了方向改变问题了吗?,当改变土地空间布局错误时
    • @famfamfam 方向没有问题,抱歉。
    猜你喜欢
    • 2014-10-27
    • 2020-07-18
    • 1970-01-01
    • 2014-07-08
    • 2017-01-05
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多