gpt4 book ai didi

ios - UICollectionViewFlowLayout 将节标题放在左插图部分

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:36 27 4
gpt4 key购买 nike

我正在尝试修改 UICollectionViewFlowLayout(垂直滚动),以便将每个部分标题放置在该部分所有项目的左侧(而不是顶部,这是默认设置)。

也就是说,这是默认行为:

Default Behaviour

...这就是我想要的:

Desired Result

所以我继承了 UICollectionViewFlowLayout:

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesToReturn = super.layoutAttributesForElementsInRect(rect) else {
return nil
}

// Copy to avoid the dreadded "Cached frame mismatch" runtime warning:
var copiedAttributes = [UICollectionViewLayoutAttributes]()

for attribute in attributesToReturn {
copiedAttributes.append(attribute.copy() as! UICollectionViewLayoutAttributes)
}

for attributes in copiedAttributes {
if let kind = attributes.representedElementKind {
// Non nil: It is a supplementary View

if kind == UICollectionElementKindSectionHeader {
// HEADER

var frame = attributes.frame
frame.origin.y = frame.origin.y + frame.size.height
frame.size.width = sectionInset.left
attributes.frame = frame
}
}
else{
// Nil: It is an item
}
}
return copiedAttributes
}

另外,为了好的措施(?),我采用了协议(protocol) UICollectionViewDelegateFlowLayout 并实现了这个方法 (虽然不清楚什么优先。然后,有设置在 Storyboard文件,但那些似乎被它们的运行时副本覆盖了):

func collectionView(
collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int) -> CGSize {

let left = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset.left

return CGSizeMake(left, 1)
}

...我成功地将标题降低到其部分的第一行;但是,标题最初占用的空间保持打开状态:

Actual Result

...我能做到这一点的唯一方法是将标题 View 高度设置为 1 并将“Clips Subviews”设置为 false,以便显示标签(如果我设置高度为 0,标签不被绘制),但这绝对不是最优雅的解决方案(并且可能会闯入 - 比如说 - iOS 9.2)

也就是说,页眉的实际高度链接到部分之间的垂直空间:我不能将空间设置为零,同时保持页眉 View 的显示尺寸合理。

也许我还应该将所有部分项目向上移动(与我的标题高度相同的量)来填补这个洞?

最佳答案

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *originalAttributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *allAttributes = [NSMutableArray new];
for (UICollectionViewLayoutAttributes* attributes in originalAttributes) {
[allAttributes addObject:[attributes copy]];
}

for (UICollectionViewLayoutAttributes *attributes in allAttributes) {
NSString *kind = attributes.representedElementKind;
if (kind == UICollectionElementKindSectionHeader) {
CGRect frame = attributes.frame;
UICollectionViewLayoutAttributes *cellAttrs = [super layoutAttributesForItemAtIndexPath:attributes.indexPath];
frame.origin.x = frame.origin.x;
frame.size.height = self.sectionInset.top;
frame.size.width = cellAttrs.frame.size.width;
attributes.frame = frame;
}
}

return allAttributes;
}

关于ios - UICollectionViewFlowLayout 将节标题放在左插图部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com