• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-12 14:00:16 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

由于 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap