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

查看:1147
本文介绍了使用自动布局的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天全站免登陆