gpt4 book ai didi

ios - 子类化 UICollectionViewLayoutAttributes

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:30 25 4
gpt4 key购买 nike

我最近开始使用很棒的 UICollectionView API,取得了合理的进展,但几乎一整天都被一个问题困住了,我希望有人能帮助我:

我需要向某些单元格的属性添加一些自定义详细信息。为了做到这一点,正确的方法似乎是将 UICollectionViewLayoutAttributes 子类化并将我需要的属性添加到我的子类中。到目前为止一切顺利,除了当我返回我的 LayoutAttributesSubclass 时,我总是得到以下错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: key cannot be nil'

在尝试追踪一段时间后,我的印象是该错误与我的子类实例中的 representedElementKind 和 representedElementCategory 为 nil 有关。但是这些属性是只读的,所以我不能设置它们。我设法以某种方式通过作弊绕过错误,获取常规 UICollectionViewAttributes 实例,然后使用 object_setClass 将其更改为 LayoutAttributesSubclass,但这随后引发了大量其他问题,而且对我来说似乎相当阴暗。

简而言之,有谁知道上面的错误是什么意思,以及如何正确创建/使用 UICollectionViewLayoutAttributes 子类?

最佳答案

设置自定义属性时,您需要子类化 UICollectionViewLayoutAttributes 子类化 UICollectionViewLayout 并通过覆盖 UICollectionViewLayout 类中的 +(Class)layoutAttributesClass 来“声明”您的自定义属性子类类名。当您使用工厂方法实例化/出列布局属性对象时,系统会调用此类方法来查看是否有要提供的自定义类。

@interface YourCustomCollectionViewAttributes : UICollectionViewLayoutAttributes

@property (nonatomic) UIEdgeInsets myCustomProperty

@end

@interface YourCustomCollectionViewLayout : UICollectionViewLayout

@end

@implementation YourCustomCollectionViewLayout

+ (Class)layoutAttributesClass
{
return [IRTableCollectionViewLayoutAttributes class];
}

@end

根据文档,这是正确的,应该可以防止您遇到的特定错误。此外,当您实现自定义 iVars 时,请确保为 -(id)copyWithZone: 实现覆盖,否则 UICollectionView 将丢失您已应用于自定义 Collection View 对象的任何自定义值。

关于ios - 子类化 UICollectionViewLayoutAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535208/

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