各種資料上上都說,Xib創(chuàng)建的cell不能被繼承 但是實(shí)際中是可以被繼承.
這句話正確描述應(yīng)該是不能直接被繼承.
我這里實(shí)現(xiàn)思路總結(jié)就是: 子類cell嵌套父類的xib創(chuàng)建的cell實(shí)現(xiàn)的
以xib 創(chuàng)建的 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"];
}
經(jīng)過以上步驟,子類cell就可以通過繼承創(chuàng)建出跟父類一模一樣的cell了,但是 子類collectionVIew 的didSelectItem代理方法卻不會執(zhí)行,子類模型賦值失敗
所以進(jìn)行下一步.
3.重寫父類的模型的set方法,解決子類模型型賦值失效問題
- (void)setModel:(SuperClassModel *)model {
_model = model;
if (self.subContentView) {
self.subContentView.model = model;
}
4.重寫子類hitTest方法,當(dāng)然也可以在父類重寫,不過建議在子類重寫
- (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;
}
這樣子類就可以接受點(diǎn)擊事件了