iOSiOS Developer

Controller瘦身

2017-05-03  本文已影响24人  ys简单0

在我们使用传统的MVC设计模式的时候,通常写着写着C中的代码就会变得又多又乱,今天通过一个简单的实例来了解MVP设计模式(即Model,View,Present).
Present负责了ModelView之间的交流和沟通,相当于是他们两个之间的 桥梁,并且在Present中可以承担一些原来在Controller中的逻辑,比如数据请求等,这样在Controller中只是实现简单的依赖设置和生命周期以及代理方法即可.具体事例如下:
首先创建Model

//只是简单的设置一个`content`属性
.h
@interface MVPModel : NSObject
@property(nonatomic,strong)NSString *content;
@end
.m
@implementation MVPModel

@end

创建View

.h
//代理
@protocol MVPViewDelegate <NSObject>

-(void)btClicked:(UIButton *)bt;

@end

@interface MVPView : UIView
@property(nonatomic,strong)UILabel *label;
@property(nonatomic,strong)UIButton *bt;
@property(nonatomic,weak)id<MVPViewDelegate>delegate;
@end
.m
//重写初始化方法
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self makeUI];
    }
    return self;
}
//页面布局
-(void)makeUI{
    self.backgroundColor = [UIColor whiteColor];
    self.label = [[UILabel alloc]initWithFrame:CGRectMake(self.frame.size.width/2-80, 100, 160, 50)];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.backgroundColor = [UIColor lightGrayColor];
    _label.layer.cornerRadius = 5;
    _label.layer.masksToBounds = YES;
    [self addSubview:_label];
    
    self.bt = [UIButton buttonWithType:UIButtonTypeSystem];
    _bt.frame = CGRectMake(self.frame.size.width/2-80, 200, 160, 50);
    _bt.backgroundColor = [UIColor lightGrayColor];
    _bt.layer.cornerRadius = 5;
    [_bt setTitle:@"点我" forState:UIControlStateNormal];
    [_bt addTarget:self action:@selector(btAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_bt];
}
//点击方法
-(void)btAction:(UIButton *)bt{
    [_delegate btClicked:bt];
}

创建Present

.h
@interface Presenter : NSObject <MVPViewDelegate>
@property(nonatomic,strong)MVPModel *mvpModel;
@property(nonatomic,strong)MVPView *mvpView;

-(void)presentViewWithContent;
@end
.m
-(void)presentViewWithContent{
    self.mvpModel.content = @"123";
    self.mvpView.label.text = self.mvpModel.content;
    self.mvpView.delegate = self;
}
#pragma mark - 代理
-(void)btClicked:(UIButton *)bt{
    self.mvpModel.content = @"123456";
    self.mvpView.label.text = self.mvpModel.content;
}

在控制器中使用

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.mvpView = [[MVPView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_mvpView];
    
    self.mvpModel = [[MVPModel alloc]init];
    
    self.presenter = [[Presenter alloc]init];
    self.presenter.mvpModel = _mvpModel;
    self.presenter.mvpView = _mvpView;
    [self.presenter presentViewWithContent];
}

大概的思路和原理就是这样的,可以根据自己的实际需求在此基础上进行整改即可.

上一篇下一篇

猜你喜欢

热点阅读