OGeek|极客世界-中国程序员成长平台

标题: ios - 以编程方式创建 uicollectionview 时使用自定义 init 方法 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:00
标题: ios - 以编程方式创建 uicollectionview 时使用自定义 init 方法

由于 Storyboard 的限制,我正在以编程方式创建 UICollectionView。这一切正常,当我想添加 UICollectionViewCell 时,我执行以下操作:

[collectionView registerClass:[Cell class] forCellWithReuseIdentifier"ID"];

我想知道如何使用“Cell”类中的自定义 init 方法,因为我无法执行以下操作:

[collectionView registerClass:[[Cell class]init_custom]forCellWithReuseIdentifier"ID"];

问题:如何使用自定义 UICollectionViewCell 类中的自定义 init 方法?



Best Answer-推荐答案


如果我理解正确,那么我会为你的 Collection View 单元创建子类。

首先用你想要的一切设置你的单元格。

@interface MyCollectionViewCell : UICollectionViewCell
// Your custom cell
@end

@implementation MyCollectionViewCell
// Your custom cell
@end

然后为每个 Collection View 创建一个仅覆盖 init 的子类。

@interface MyCollectionViewCellForCollectionView1 : MyCollectionViewCell

@end

@implementation MyCollectionViewCellForCollectionView1
- (instancetype)init // Only override -init
{
    self = [super init];
    if (self) {
        // Setup for collection view one
    }
    return self;
}
@end

@interface MyCollectionViewCellForCollectionView2 : MyCollectionViewCell

@end

@implementation MyCollectionViewCellForCollectionView2
- (instancetype)init // Only override -init
{
    self = [super init];
    if (self) {
        // Setup for collection view two
    }
    return self;
}
@end

然后,为每个不同的 Collection View 注册一个子类。

[collectionView1 registerClass:[MyCollectionViewCellForCollectionView1 class] forCellWithReuseIdentifier"ID"];
[collectionView2 registerClass:[MyCollectionViewCellForCollectionView2 class] forCellWithReuseIdentifier"ID"];

这将为您提供所需的单独自定义 init 方法,但请确保将所有功能保留在基类中。

关于ios - 以编程方式创建 uicollectionview 时使用自定义 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28252912/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4