gpt4 book ai didi

ios - 子类化 UICollectionViewFlowLayout - iOS 12 中自动调整单元格框架计算问题

转载 作者:可可西里 更新时间:2023-11-01 00:54:34 24 4
gpt4 key购买 nike

我正在使用以下内容在 UICollectionView 中左对齐单元格…

class LeftAlignedFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }

for attributes in attributes where attributes.representedElementCategory == .cell {
attributes.frame = layoutAttributesForItem(at: attributes.indexPath).frame
}
return attributes
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes {
let currentItemAttributes = super.layoutAttributesForItem(at: indexPath)!

let layoutWidth = collectionView!.frame.width - sectionInset.left - sectionInset.right

// Just left align the first item in a section
if indexPath.item == 0 {
currentItemAttributes.frame.origin.x = sectionInset.left
return currentItemAttributes
}

let previousIndexPath = IndexPath(item: indexPath.item - 1, section: indexPath.section)
let previousItemFrame = layoutAttributesForItem(at: previousIndexPath).frame

let currentItemFrame = currentItemAttributes.frame
let wholeRowFrameForCurrentItem = CGRect(x: sectionInset.left, y: currentItemFrame.minY, width: layoutWidth, height: currentItemFrame.height)

// Left align the first item on a row
if !previousItemFrame.intersects(wholeRowFrameForCurrentItem) {
currentItemAttributes.frame.origin.x = sectionInset.left
return currentItemAttributes
}

currentItemAttributes.frame.origin.x = previousItemFrame.maxX + minimumInteritemSpacing
return currentItemAttributes, it's
}
}

为 iOS 11 构建提供......

enter image description here

但是对于 iOS 12 来说……

enter image description here

在 iOS 11 中,layoutAttributesForElements(in) 被调用 3 次 - 最后一次具有正确的帧大小。在 iOS 12 中,它只被调用两次,帧是估计的大小。

根据这个答案,https://stackoverflow.com/a/52148520/123632我尝试使用下面的 UICollectionView 子类(以及包含 View Controller 的 viewDidAppear 中的“暴力破解”)使流布局无效,但结果没有改变。

class LeftAlignedCollectionView: UICollectionView {

private var shouldInvalidateLayout = false

override func layoutSubviews() {
super.layoutSubviews()
if shouldInvalidateLayout {
collectionViewLayout.invalidateLayout()
shouldInvalidateLayout = false
}
}

override func reloadData() {
shouldInvalidateLayout = true
super.reloadData()
}
}

最佳答案

这是 iOS 12 中的一个已知问题(请参阅此处的 UIKit 部分:https://developer.apple.com/documentation/ios_release_notes/ios_12_release_notes)

解决方法是在调用 systemLayoutSizeFitting(_:) 之前避免调用 setNeedsUpdateConstraints() 或调用 updateConstraintsIfNeeded()

关于ios - 子类化 UICollectionViewFlowLayout - iOS 12 中自动调整单元格框架计算问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52368197/

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