【问题标题】:Subclassing custom UICollectionViewCell子类化自定义 UICollectionViewCell
【发布时间】:2016-07-21 14:07:36
【问题描述】:

我已成功创建具有 3 个标签的自定义 UICollectionViewCell。

现在我想继承它,添加 dateToDisplay 属性并在 setDateToDisplay 中更改标签的字符串(使用自定义日期格式化程序)。

parentCell的创建和使用:

ParentCellIdentifier.h    
static NSString *ParentCellIdentifier = @"ParentCellIdentifier";

@interface ParentCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UILabel *firstLabel;
@property (strong, nonatomic) IBOutlet UILabel *secondLabel;
@property (strong, nonatomic) IBOutlet UILabel *thirdLabel;

-(void)setupDefaults;
@end

在 parentCell.xib 中:

类设置为ParentCell,标识符设置为ParentCellIdentifier

在 ViewController 我有 UICollectionView:

-(void)setupCollectionView {
     [_daysCollectionView registerNib:[UINib nibWithNibName:@"ParentCell" bundle:nil] forCellWithReuseIdentifier:ParentCellIdentifier];
    _daysCollectionView.delegate = self;
    _daysCollectionView.dataSource = self;
    _daysCollectionView.backgroundColor = [UIColor clearColor];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ParentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ParentCellIdentifier forIndexPath:indexPath];
    cell.firstLabel.text = @"first";
    cell.secondLabel.text = @"second";
}

上面的设置就像一个魅力。 不,我想添加 ChildCell,使用与以前相同的 xib:

@interface ChildCell : ParentCell
@property (nonatomic, strong) NSDate* dateToDislpay;//labels of parentCell updated using dateformatters on setDateToDisplay:
@end

-(void)setupCollectionView 保持不变,为 ParentCellIdentifier 注册 ParentCell.xib

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ChildCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ParentCellIdentifier forIndexPath:indexPath];
    NSDate* date = [_dates objectAtIndex:indexPath.row];
    cell.dateToDislpay = date; //here goes the error

尝试设置子单元格的属性时,它会崩溃。这是正确的,因为在 ParentCell.xib 类中的单元格是 ParentCell。 更改 xib 中的类后,它可以工作,但我想坚持使用 xib 中的父类,因为我将使用相同的 xib,但仅使用不同的格式化程序。

我该怎么做?

EDIT1: 收到崩溃:

-[ParentCell setDateToDislpay:]: unrecognized selector sent to instance

【问题讨论】:

  • 什么是崩溃请发布错误
  • 添加编辑:它是发送到实例的无法识别的选择器。

标签: ios objective-c iphone uicollectionview


【解决方案1】:

您需要进入 xib 文件并将类类型更改为 ChildCell,这应该可以解决您的崩溃问题。

子类见这里:https://stackoverflow.com/a/5056886/848719

您必须覆盖 initWithFrame:awakeFromNib

【讨论】:

  • 我就是这么做的。但是,我想坚持使用 xib 中的 ParentClass,因为我将使用父 xib 为标签创建具有不同格式化程序的多个子类。
【解决方案2】:

您崩溃了,因为您注册了 [UINib nibWithNibName:@"ParentCell" bundle:nil] Parent Cell 并且在单元格中为项目创建了 ChildCell 的对象,但它是父单元格而不是子单元格 并且父单元格没有dateToDislpay 属性。

您可以使用打印类检查相同的内容

你的继承方式不对,你应该阅读一些教程或阅读一些演示

【讨论】:

  • 我知道,我在我的问题中提到了它。真正的问题是如何为不同类别的视图使用相同的 xib。
  • 我没有理由在这里看到你为什么要使用父单元格,父单元格包含弱的 IBOutlets
猜你喜欢
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多