各种资料上上都说,Xib创建的cell不能被继承 但是实际中是可以被继承.
这句话正确描述应该是不能直接被继承.
我这里实现思路总结就是: 子类cell嵌套父类的xib创建的cell实现的
以xib 创建的 collectionCell 为例
1. 在父类cell中给父类cell添加一个属性,类型为父类cell
@interface DTMyCourseCell : UICollectionViewCell
@property(nonatomic, assign) DTMyCourseCell *subContentView;
@end
2.重写父类cell initWithFrame方法
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self loadViewFromNib];
//
}
return self;
}
- (void)loadViewFromNib {
UINib *nib = [UINib nibWithNibName:@"DTMyCourseCell" bundle:[NSBundle mainBundle]];
DTMyCourseCell *newContentView = [nib instantiateWithOwner:self options:nil].firstObject;
newContentView.frame = self.contentView.frame;
self.subContentView = newContentView;
[self setValue:newContentView forKey:@"contentView"];
}
经过以上步骤,子类cell就可以通过继承创建出跟父类一模一样的cell了,但是 子类collectionVIew 的didSelectItem代理方法却不会执行,子类模型赋值失败
所以进行下一步.
3.重写父类的模型的set方法,解决子类模型型赋值失效问题
- (void)setModel:(SuperClassModel *)model {
_model = model;
if (self.subContentView) {
self.subContentView.model = model;
}
4.重写子类hitTest方法,当然也可以在父类重写,不过建议在子类重写
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView *view = [super hitTest:point withEvent:event];
if (view) {
if ([view isKindOfClass:[UIButton class]]) {
return view;
}
for (UIView* next = [view superview]; next; next = next.superview) {
UIResponder* nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[self class]]) {
return (UIView *)nextResponder;
}
}
}
return view;
}
这样子类就可以接受点击事件了
网友评论