Ios 如何根据UILabel动态调整CollectionViewCell的大小
我正在创建建议/标记视图。它基本上是一个水平的Ios 如何根据UILabel动态调整CollectionViewCell的大小,ios,swift,uicollectionview,uilabel,uicollectionviewcell,Ios,Swift,Uicollectionview,Uilabel,Uicollectionviewcell,我正在创建建议/标记视图。它基本上是一个水平的uicollectionview。我有一个自定义单元格,其中只有一个标签,没有自动调整大小或自动约束。我有一个数组var tagsArray=[“Label”,“一个Long Label”,“一个very Long Label”],我在集合视图委托方法中使用它: func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&
uicollectionview
。我有一个自定义单元格,其中只有一个标签,没有自动调整大小或自动约束。我有一个数组var tagsArray=[“Label”,“一个Long Label”,“一个very Long Label”]
,我在集合视图委托方法中使用它:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tagsArray.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = (tagsArray[indexPath.row] as NSString).size(withAttributes: nil)
return size
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell", for: indexPath) as! TagCollectionViewCell
cell.tagLabel.text = tagsArray[indexPath.row]
return cell
}
第二个函数collectionViewLayout
是我从堆栈溢出中选择的,但运行它时对UILabel没有影响。
以下是输出:
您不需要计算要显示的字符串的大小。请执行以下操作:
tagLabel
的前导
,尾随
,顶部
和底部
约束设置为与相应单元格的内容视图
约束相等func collectionView(\ucollectionview:UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexath:indexPath)->CGSize的实现。如果不为estimatedItemSize
使用自定义值,将自动计算单元格大小。如果要确定,请将(collectionView.collectionViewLayout作为?UICollectionViewFlowLayout)?.estimatedItemSize=UICollectionViewFlowLayout.automaticSize
添加到设置所有视图的函数中
您可以将此库用于标记视图:添加输出图像。@dahiya_boy添加了输出图像。@Chaudhrytaha您需要使用它来获取字符串的确切宽度。在这之后添加一些边距,以便您的UI看起来很好。我在Obj-c中也做了同样的操作,因为它只有一行代码,所以你也可以将它转换成swift。@dahiya_boy我已经添加了
让tagSize=(tagsArray[indexPath.row]作为NSString)。boundingRect(使用:(tagsArray[indexPath.row]作为NSString)。size(使用属性:nil),选项:.usesLineFragmentOrigin,属性:nil,上下文:nil).size
通过遵循objective c链接,然后返回CGSize(宽度:tagSize.width,高度:40)
在sizeForItemAt
函数中,但它仍然不起作用。@LalKrishna在iOS 11和iOS 12上尝试了这段代码,效果很好。如果contentView
没有在xib中显示,如何处理它?@VyachaslavGerchicov我想你应该问一个新问题。你也可以用。不,我想你的答案是incomplete@VyachaslavGerchicovcontentView
应该在xib文件中可见。还是你出于某种原因把它藏起来了?