iOS之基于MVP架构实现view的复用

场景:如果一个包含头像、名字、自我介绍文案的自定义view在不同的列表cell的contentView中都存在,那么我们每个cell里都要去依赖这个view,但是可能不同列表的数据源模型model是不同的,那么我们需要cell.model = model赋值时,对于这个view而言,就有多个model对象,这样的代码就有点让人受不了,同一个给子控件赋值的操作因为model不同就要做多遍,怎么处理?

由于MVP架构中的P,可以实现V和M的解耦,原理是:protocal是针对于view渲染所需要的数据来设置的协议,也就是说view子控件所需要的直接数据都可以在protocal中找到,那协议中的数据从哪里来呢?这个就要从遵守这个协议的model类中获取,在model类的.m文件中,去给协议里的这些字段赋值,当然赋值的依据来自于model的数据(直接赋值或者经过计算后赋值)。
这样看来对于view来说没有依赖model,依赖的是遵循了协议的model,不管是哪个model,只要遵循了协议实现了协议中属性的赋值就可以,此时view中是不需要引入哪个model的头文件的,说明实现了V和M的解耦

整个项目结构

protocal协议

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@protocol SJTableBaseModelProtocol <NSObject>
//这里都是view中可以直接赋值的一些属性
@required
@property (nonatomic,copy,readonly) NSString *name;
///对于个人的描述
@property (nonatomic,copy,readonly) NSString *content;
@property (nonatomic,copy,readonly) NSString *ageStr;
@property (nonatomic,assign,readonly) BOOL isShow;
@end

NS_ASSUME_NONNULL_END

一个基础的view类,用于设置公用属性

#import <UIKit/UIKit.h>
#import "SJTableBaseModelProtocol.h"
NS_ASSUME_NONNULL_BEGIN
static CGFloat kBaseCellSubViewLeftMargin = 12.0; //cell内容统一的左边距


@interface SJCellBaseView : UIView

- (void)configWithData:(id <SJTableBaseModelProtocol>)model;
+ (CGFloat)fetchHeightWithData:(id <SJTableBaseModelProtocol>)model;

@end

NS_ASSUME_NONNULL_END
#import "SJCellBaseView.h"

@implementation SJCellBaseView

- (void)configWithData:(id <SJTableBaseModelProtocol>)model {
}

+ (CGFloat)fetchHeightWithData:(id <SJTableBaseModelProtocol>)model {
    return 0;
}
@end

继承与SJCellBaseView的子类

@interface SJCellDiyContentView : SJCellBaseView
//点击事件由外部处理
@property (nonatomic, copy) dispatch_block_t clickSeeMoreBlock;
@end

NS_ASSUME_NONNULL_END
@interface SJCellDiyContentView ()

@property (nonatomic, strong) YYLabel *contentLabel;

@end

@implementation SJCellDiyContentView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self configViews];
    }
    return self;
}

- (void)configViews {
    [self addSubview:self.contentLabel];
}

- (void)configWithData:(id < SJTableBaseModelProtocol >)model {
  //赋值渲染操作
      ...
//赋值的时候直接计算一下自己的高度,供外层控件布局使用
  self.height = [[self class] fetchHeightWithData:model];
}

+ (CGFloat)fetchHeightWithData:(id < SJTableBaseModelProtocol >)model {
//根据model赋值完,计算控件的高度
    return 40;
}

#pragma mark - Getter
- (YYLabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[YYLabel alloc] init];
        _contentLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
        _contentLabel.displaysAsynchronously = YES;
        _contentLabel.ignoreCommonProperties = YES;
        _contentLabel.fadeOnAsynchronouslyDisplay = NO;
        _contentLabel.fadeOnHighlight = NO;
        @weakify(self)
        _contentLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            @strongify(self);
            [self clickNicknameWithText:text range:range];
        };
    }
    return _contentLabel;
}

@end

后续还有多个可复用view的开发,都继承与SJCellBaseView,这样就可以使用父类- (void)configWithData:(id < SJTableBaseModelProtocol >)model {}+ (CGFloat)fetchHeightWithData:(id < SJTableBaseModelProtocol >)model {}赋值和获取高度方法
假如我们后续又添加了两个自定义viewSJCellDiyContentView_two SJCellDiyContentView_three

基础的UITableViewCell类

@interface SJBaseTableViewCell : UITableViewCell

- (void)configWithData:(id <SJTableBaseModelProtocol>)model;

+ (CGFloat)fetchHeightWithData:(id < SJTableBaseModelProtocol >)model;

// 子类重写此方法,配置好所有模块,按照从上到下的顺序
+ (NSArray *)myComponents;

#pragma mark - 业务交互方法,Cell子类实现
- (void)didClickHead;
- (void)didClickCancleAdvertising;
...
@interface SJBaseTableViewCell ()
@property (nonatomic, strong) NSArray *cellComponents;

//将相似tableviewcell中的控件都放在基础cell中,根据子类的cellComponents方法中添加子控件种类来添加子控件
@property (nonatomic, strong) SJCellDiyContentView *cellDiyContentView;
@property (nonatomic, strong) SJCellDiyContentView_two * cellDiyContentView_two;
@property (nonatomic, strong) SJCellDiyContentView_three * cellDiyContentView_three;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation SJBaseTableViewCell
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]){
        self.cellComponents = [[self class] myComponents];
        [self configViews];
    }
    return self;
}

- (void)configViews {
//子类中通过myComponents方法中添加枚举值得方式,添加子视图,在父视图这里择情况从上往下添加子视图
//继承与该cell的子类可以包含多种组合方式
    for (int i = 0; i < [self.cellComponents count]; i++) {
        NSNumber *num = [self.cellComponents objectAtIndex:i];
        
        switch (num.integerValue) {
            //自定义view的枚举值
            case kSJCellDiyContentView:
                [self.contentView addSubview:self.cellDiyContentView];
                break;
            //自定义view2的枚举值
            case kSJCellDiyContentView_two:
                [self.contentView addSubview:self.cellDiyContentView_two];
                break;
            //自定义view3的枚举值
            case kSJCellDiyContentView_three:
                [self.contentView addSubview:self.cellDiyContentView_three];
                break;
            default:
                break;
        }
    }
    
//self.bottomView用于封底
    [self.contentView addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.contentView);
        make.height.equalTo(@(10));
    }];
}

- (void)configWithData:(id < SJTableBaseModelProtocol >)model {
    CGFloat bottom = 0;
    
    for (int i = 0; i < [self.cellComponents count]; i++) {
        NSNumber *num = [self.cellComponents objectAtIndex:i];
        switch (num.integerValue) {
            //自定义view的枚举值
            case kSJCellDiyContentView:
                [self.cellDiyContentView configWithData:model];
                self.cellDiyContentView.frame = CGRectMake(0, bottom, kScreenWidth, self.cellRecommendHeadView.height);
                bottom = bottom + self.cellDiyContentView.height;
                break;
            //自定义view2的枚举值
            case kSJCellDiyContentView_two:
                [self.cellDiyContentView_two configWithData:model];
                self.cellDiyContentView_two.frame = CGRectMake(0, bottom, kScreenWidth, self.cellDiyContentView_two.height);
                bottom = bottom + self.cellDiyContentView_two.height;
                break;
            //自定义view3的枚举值
            case kSJCellDiyContentView_three:
                [self.cellDiyContentView_three configWithData:model];
                self.cellDiyContentView_three.frame = CGRectMake(0, bottom, kScreenWidth, self.cellDiyContentView_three.height);
                bottom = bottom + self.cellDiyContentView_three.height;
                break;
            default:
                break;
        }
    }
}

+ (CGFloat)fetchHeightWithData:(id < SJTableBaseModelProtocol >)model {
    CGFloat height = 0;
    
    for (int i = 0; i < [[[self class] myComponents] count]; i++) {
        NSNumber *num = [[[self class] myComponents] objectAtIndex:i];
        
        switch (num.integerValue) {
            //自定义view的枚举值
            case kSJCellDiyContentView:
                height = height + [SJCellDiyContentView fetchHeightWithData:model];
                break;
            //自定义view2的枚举值
            case kSJCellDiyContentView_two:
                height = height + [SJCellDiyContentView_two fetchHeightWithData:model];
                break;
            //自定义view3的枚举值
            case kSJCellDiyContentView_three:
                height = height + [SJCellDiyContentView_three fetchHeightWithData:model];
                break;
            default:
                break;
        }
    }
    height = height + 10 + 15; // 10 为self.bottomView 高度,15 为距离self.bottom 顶部的间距
    return height;
}

#pragma mark - lazyload
子控件的懒加载区域

#pragma mark - 交互方法,子类实现
+ (NSArray *)myComponents {
    return @[];
}
//view中的点击事件在本类中先不实现,对外提供接口,让子类实现
- (void)didClickHead {}
- (void)didClickCancleAdvertising {}

使用 :我们有一个cell样式是由SJCellDiyContentView_twoSJCellDiyContentView_three组合的

新建一个cell类,比如customTableviewCell继承自SJBaseTableViewCell

NS_ASSUME_NONNULL_BEGIN

@interface customTableviewCell : SJBaseTableViewCell

@end

NS_ASSUME_NONNULL_END
@implementation customTableviewCell
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupData];
    }
    return self;
}

#pragma mark - 本cell包含的所有模块
+ (NSArray *)myComponents {
    //对于父类的所有子控件来说,本cell只包含了这两种view,所以只加这两种枚举,从上往下加
    return @[@(kSJCellDiyContentView_two),
             @(kSJCellDiyContentView_three),];
}

- (void)configWithData:(id<SJTableBaseModelProtocol>)model {
    //调用父类的赋值方法
    [super configWithData:model];
}

+ (CGFloat)fetchHeightWithData:(id < SJTableBaseModelProtocol >)model{
    return [super fetchHeightWithData:model];
}

//这里就可以实现父类中在本cell中的具体触发到的点击事件了
- (void)didClickHead{
    //具体实现。。。
}

model类的操作

#import <Foundation/Foundation.h>
#import "SJTableBaseModelProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface DiyModel : NSObject< SJTableBaseModelProtocol >

@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *content;
@property (nonatomic,assign) NSInteger age;
@end

NS_ASSUME_NONNULL_END
#import "DiyModel.h"

@implementation DiyModel
//在类中遵循了代理,就要实现协议里那些属性的赋值,给到协议的值是view可以直接用的
- (NSString *)name{
    return [NSString stringWithFormat:@"我的名字叫:%@",_name];
}


- (NSString *)ageStr{
    return [NSString stringWithFormat:@"%ld",self.age];
}

//如果不用处理直接赋值的,注意嵌套循环造成死循环,比如这里就不能return self.content,会造成自身一直在嵌套循环
- (NSString *)content{
    return _content;
}

- (BOOL)isShow{
    if (self.age > 18) {
        return YES;
    }else{
        return NO;
    }
}
@end

其他cell的使用

其他列表cell的数据源不同,只要也遵循协议,并把协议的属性通过自己model的属性经过处理赋值,那么就还是可以用户我们的view渲染试图方法- (void)configWithData:(id<SJTableBaseModelProtocol>)model因为我们要的只是遵循了SJTableBaseModelProtocol的东西,不关系他是什么

总结:用这种方式,就像堆积木一样,首先cell的子控件是通用的,我基础cell组建里包含了所有种子控件,使用的时候只要通过枚举去添加我们所需要的控件就OK了,然后网络请求好的数据封装model后传值给cell即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容