如何解决iOS:集合视图自定义标签布局动态Height Swift
我正在尝试创建标签列表视图。不幸的是,我不知道如何使用自定义流布局。但是我发现创建漂亮的标签列表。但是遇到多行标签问题。如果我们使用的文字多于集合视图的宽度,那么attribute.frame.height
应该像40*numberOfLines
那样相乘。请帮助解决此问题。
自定义流布局:
import UIKit
class CollectionViewRow {
var attributes = [UICollectionViewLayoutAttributes]()
var spacing: CGFloat = 0
init(spacing: CGFloat) {
self.spacing = spacing
}
func add(attribute: UICollectionViewLayoutAttributes) {
attributes.append(attribute)
}
var rowWidth: CGFloat {
return attributes.reduce(0,{ result,attribute -> CGFloat in
return result + attribute.frame.width
}) + CGFloat(attributes.count - 1) * spacing
}
func layout(collectionViewWidth: CGFloat) {
var offset = spacing
for attribute in attributes {
attribute.frame.origin.x = offset
offset += attribute.frame.width + spacing
}
}
}
class UICollectionViewCenterLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else {
return nil
}
var rows = [CollectionViewRow]()
var currentRowY: CGFloat = -1
for attribute in attributes {
if currentRowY != attribute.frame.midY {
currentRowY = attribute.frame.midY
rows.append(CollectionViewRow(spacing: 10))
}
rows.last?.add(attribute: attribute)
}
rows.forEach { $0.layout(collectionViewWidth: collectionView?.frame.width ?? 0) }
return rows.flatMap { $0.attributes }
}
}
用法:
let layout = UICollectionViewCenterLayout()
layout.estimatedItemSize = CGSize(width: 140,height: 40)
collectionView.collectionViewLayout = layout
collectionView.reloadData()
我尝试更改高度,但无法正常工作:
func layout(collectionViewWidth: CGFloat) {
var offset = spacing
for attribute in attributes {
attribute.frame.origin.x = offset
let attributeTotalWidth = attribute.frame.width + spacing
if attributeTotalWidth > collectionViewWidth{
let multiplier: CGFloat = attributeTotalWidth/collectionViewWidth
let intVal = CGFloat(Int(multiplier))
let fullNumber = multiplier-intVal > 0 ? intVal+1 :
attribute.frame.size.height = fullNumber * 40
}
offset += attributeTotalWidth
}
}
能否请您帮我找出基于标签文本内容使商品高度可变的解决方案?预先感谢您!
解决方法
@iDeveloper我试图修复您的代码。
这是您可以做的事情。
-
简化阵列。
标题名称= [“ Apple”,“ Google”,“计算机”,“终端”,“毛额”,“表格土地”,“水土地”,“河流”,“山峰”,“树木”,“地方”,“公园”,“城镇”,“城市”,“ Lorem Ipsum只是印刷和排版行业的伪文本。”,“ Hello”,“ A”,“ B”,“ CAD”,“ John”, “ Nick”,“ Lucas”,“ Amy”,“ Lawrance”,“ Apple”,“ Google”,“ Computer”,“ Browser”,“ Overflow”,“ Hi”,“ Hello”,“ A”,“ B” “,” CAD“,” John“,” Nick“,” Lucas“,” Amy“,” Lawrance“,” Lorem Ipsum只是印刷和排版行业的伪文本。“,”“]
-
您必须像这样在标题标签上添加宽度限制。
- 设置标签的内容优先级
最终结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。