我一直在尝试创建一个水平呈现标签的集合视图,分为两行。用户可以水平滚动以查看更多标签。完全像Bandcamp应用程序中的过滤器 https://itunes.apple.com/us/app/bandcamp/id706408639?mt=8
通过自定义UICollectionViewFlowLayout,我找到了一个关于如何做类似事情的非常好的教程。 https://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/
但是,本教程适用于垂直集合视图,可根据需要创建行。我需要的是标签向右流动,并将布局约束为两行。
这是教程
中UICollectionViewFlowLayout的片段class FlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributesForElementsInRect = super.layoutAttributesForElementsInRect(rect)
var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()
var leftMargin: CGFloat = 0.0;
for attributes in attributesForElementsInRect! {
if (attributes.frame.origin.x == self.sectionInset.left) {
leftMargin = self.sectionInset.left
} else {
var newLeftAlignedFrame = attributes.frame
newLeftAlignedFrame.origin.x = leftMargin
attributes.frame = newLeftAlignedFrame
}
leftMargin += attributes.frame.size.width + 8
newAttributesForElementsInRect.append(attributes)
}
return newAttributesForElementsInRect
}
}
THX!
答案 0 :(得分:3)
所以,我终于设法为我的问题编写了一个解决方案:在prepareLayout上,我将X / Y位置重新分配给我的单元格,以及我的内容宽度,然后我更新LayoutAttributes上的属性。诀窍是拥有一个包含两行信息的变量,并相应地更改每个单元格。这是遇到类似问题的人的代码
return fetch(
'http://localhost:8000/login',
{ method: 'POST',
mode: 'no-cors',
headers: new Headers(
{"Content-Type": "application/json",
"Accept":"application/json"}
),
body: JSON.stringify(
{'name': 'Tom', 'password': 'Soyer'}
)
}
).then( response => { console.log(response);})
.catch(err => console.log(err))
答案 1 :(得分:0)
修改您的代码以使其正确对齐
class FlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributesForElementsInRect = super.layoutAttributesForElementsInRect(rect)
var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()
var rightMargin: CGFloat = rect.width;
for attribute in attributesForElementsInRect! {
attribute.frame.origin.x = rightMargin - attribute.frame.width - 8
if attribute.frame.origin.x <= self.sectionInset.left {
rightMargin = rect.width - self.sectionInset.right
attribute.frame.origin.x = rightMargin - attribute.frame.width
}
rightMargin = rightMargin - attribute.frame.size.width - 8
newAttributesForElementsInRect.append(attribute)
}
return newAttributesForElementsInRect
}
}
答案 2 :(得分:0)
我能够修改最初由 Włodzimierz Woźniak 创建的代码库,以便我可以水平滚动 UITableViewCell 中的标签标签。以编程方式添加 UIScrollView 作为 UITableViewCell 中的子视图几乎肯定可以为 UICollectionViewFlowLayout 实现。
以下是代码工作原理的细分...
你可以在这里找到一个可行的实现演示: