如何创建水平动态 UICollectionView 单元格?迅速 [英] How to create horizontally dynamic UICollectionView cells? Swift

查看:10
本文介绍了如何创建水平动态 UICollectionView 单元格?迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在尝试使用集合视图单元格在视图控制器中显示一组标签",但我无法找到一种方法使它们能够根据字符串的长度动态调整大小.

Hey I'm trying display a set of "tags" in a view controller using collection view cells but I'm having trouble finding a way to make them be able to dynamically resizable depending on the length of the string.

现在各个单元格的大小是静态的,所以每当一个字符串填充单元格的字符超过单元格的大小时,它就会进入第二行.我想要它,以便单元格可以根据字符串的长度改变长度.因此,如果它是标签#Vegan",它会自动调整大小,使标签不会那么大.同样,如果它是一个较长的字符串,如#LaptopFriendly",它会在水平方向变长以容纳该字符串并且不使用第二行.垂直长度可以保持固定.谢谢!

Right now the individual cells are statically sized so whenever a String that populates the cell with characters exceeding the size of the cell, it goes into the second line. I want it so that the cell can change length depending on the length of the String. So if it's the tag "#Vegan", it will automatically resize so that the tag isn't that big. Likewise, if it's a longer string like "#LaptopFriendly", it will become horizontally longer to accommodate the string and not use the second line. The vertical length can stay fixed. Thank you!

更新(当我使用 Rob 的代码遇到错误时的界面构建器设置):

模拟器截图:

推荐答案

标签和单元格之间需要明确的约束(例如前导、尾随、顶部和底部约束):

You need unambiguous constraints between your label and the cell (e.g. leading, trailing, top, and bottom constraints):

然后您可以将 UICollectionViewFlowLayoutAutomaticSize 用于您的 collectionViewLayoutitemSize.不要忘记设置 estimatedItemSize,它可以自动调整单元格大小:

Then you can use UICollectionViewFlowLayoutAutomaticSize for the itemSize of your collectionViewLayout. Don't forget to set estimatedItemSize, too, which enables automatically resizing cells:

override func viewDidLoad() {
    super.viewDidLoad()

    let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
    layout.estimatedItemSize = CGSize(width: 100, height: 40)
}

产生:

这篇关于如何创建水平动态 UICollectionView 单元格?迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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