使用自动布局的 UICollectionView 标题动态高度 [英] UICollectionView header dynamic height using Auto Layout

查看:55
本文介绍了使用自动布局的 UICollectionView 标题动态高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UICollectionView,其标题类型为 UICollectionReusableView.

I have a UICollectionView with a header of type UICollectionReusableView.

在其中,我有一个标签,其长度因用户输入而异.

In it, I have a label whose length varies by user input.

我正在寻找一种方法,可以根据标签的高度以及标题中的其他子视图动态调整标题的大小.

I'm looking for a way to have the header dynamically resize depending on the height of the label, as well as other subviews in the header.

这是我的故事板:

这是我运行应用程序时的结果:

This the result when I run the app:

推荐答案

这是一个优雅的最新解决方案.

Here's an elegant, up to date solution.

正如其他人所说,首先确保所有约束都从标题视图的最顶部到第一个子视图的顶部,从第一个子视图的底部到第二个子视图的顶部,等等,从最后一个子视图的底部到标题视图的底部.只有这样,自动布局才能知道如何调整视图大小.

As stated by others, first make sure that all you have constraints running from the very top of your header view to the top of the first subview, from the bottom of the first subview to the top of the second subview, etc, and from the bottom of the last subview to the bottom of your header view. Only then auto layout can know how to resize your view.

截取的以下代码返回标题视图的计算大小.

The following code snipped returns the calculated size of your header view.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

    // Get the view for the first header
    let indexPath = IndexPath(row: 0, section: section)
    let headerView = self.collectionView(collectionView, viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader, at: indexPath)

    // Use this view to calculate the optimal size based on the collection view's width
    return headerView.systemLayoutSizeFitting(CGSize(width: collectionView.frame.width, height: UIView.layoutFittingExpandedSize.height),
                                              withHorizontalFittingPriority: .required, // Width is fixed
                                              verticalFittingPriority: .fittingSizeLevel) // Height can be as large as needed
}

编辑

正如@Caio 在评论中所注意到的,此解决方案将导致 iOS 10 及更早版本崩溃.在我的项目中,我通过将上面的代码包装在 if #available(iOS 11.0, *) { ... } 并在 else 子句中提供固定大小来解决"这个问题.这并不理想,但在我的情况下是可以接受的.

Edit

As @Caio noticed in the comments, this solution will cause a crash on iOS 10 and older. In my project, I've "solved" this by wrapping the code above in if #available(iOS 11.0, *) { ... } and providing a fixed size in the else clause. That's not ideal, but acceptable in my case.

这篇关于使用自动布局的 UICollectionView 标题动态高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆