ios - 以编程方式创建 uicollectionview 时使用自定义 init 方法

标签 ios objective-c uicollectionview uicollectionviewcell

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

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

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

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

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

最佳答案

如果我理解正确,那么我会创建您的 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/

相关文章:

iphone - 如何从 uiviewcontroller 加载类中的方法

ios - 尝试上传到 iTunes Connect 时找不到最新的 iTMSTransporter 下载 Bad Gateway

objective-c - 操作系统 : "Window Server: failed setting the front application to My App"

ios - 最后 UICollectionViewCell 对齐

ios - 解析 UICollectionView 的查询不工作

ios - 多个按钮未出现在 UICollectionViewCell 中

ios - 在选项卡式应用程序中保存用户对选项卡的重新排序

iPhone 配置实用程序 - 禁用相机应用程序还会禁用 ImagePicker

objective-c - NSSortDescriptor:同时对多个键进行自定义比较

ios - UIcollectionView cellForItemAtIndexPath 仅在 iOS 10 中返回 Null。在 iOS 9 和 iOS 8 中运行良好