gpt4 book ai didi

ios - 访问 Layout 对象中 CollectionView 的布局属性

转载 作者:行者123 更新时间:2023-11-29 05:46:22 25 4
gpt4 key购买 nike

我实现了 UICollectionViewFlowLayout 的子类,它只重写一个方法 func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint 。在这个方法中,我打算访问已渲染的collectionview的当前布局属性,例如:itemSize、sectionInsets等。

但是,当我尝试像self.itemSize这样访问它时,它返回一个默认值。

Apple Docs 要求 CollectionView Delegate 为每个属性实现相应的委托(delegate)方法,例如:

If the delegate does not implement the collectionView:layout:sizeForItemAtIndexPath: method, the flow layout object uses the value of this property to set the margins for each section.

我已经在我的 View Controller 中实现了所有这些委托(delegate)方法。

现在我的问题是这些值不会设置底层 CollectionViewFlowLayout 对象的属性吗?它是否总是检查委托(delegate)是否响应特定的相应选择器并避免将该值存储在相应的属性中?

这是访问 CollectionView 的流对象中的布局属性的正确方法吗?

let delegate = self.collectionView!.delegate as! UICollectionViewDelegateFlowLayout
let itemSize = delegate.collectionView(<#T##collectionView: UICollectionView##UICollectionView#>, layout: <#T##UICollectionViewLayout#>, sizeForItemAt: <#T##IndexPath#>)

如果是的话,为什么这是一个如此冗长的方法?如果没有,我错过了什么?

最佳答案

如果所有单元格的大小相同,那么您应该设置 itemSize 而不是使用委托(delegate)方法。您可以通过选择 Collection View 、选择大小检查器并设置单元格大小在界面生成器中进行设置。或者您可以在 UICollectionViewFlowLayout 子类的生命周期的早期进行设置。

如果单元格的大小是动态的,那么您需要调用委托(delegate)方法来确定大小。您是对的,您需要通过 Collection View 访问委托(delegate)。这可能是因为 UICollectionViewDelegateFlowLayout 扩展了 UICollectionViewDelegate。添加辅助访问器,例如:

var delegate: UICollectionViewDelegateFlowLayout? {
return collectionView?.delegate as? UICollectionViewDelegateFlowLayout
}

可以使这更容易使用。

但是,当布局无效时,您实际上应该只需要向委托(delegate)询问大小信息。似乎 layoutAttributesForItem(at: indexPath)layoutAttributesForElements(in: rect) 可用于确定已布局项目的大小信息。这两个都是 UICollectionViewFlowLayout 上的方法。

关于ios - 访问 Layout 对象中 CollectionView 的布局属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56118777/

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