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

查看:85
本文介绍了如何创建水平动态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的代码遇到错误时的界面构建器设置):

模拟器截图:

Simulator screenshot:

推荐答案

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

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

然后你可以使用 UICollectionViewFlowLayoutAutomaticSize 获取 itemSize collectionViewLayout 的。不要忘记设置 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天全站免登陆