MVVM设计模式实例

项目结构:

ViewController:

- (void)viewDidLoad {
    [super viewDidLoad];
    _vModel = [MyViewModel new];
    _myView = [[MyView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_myView];
     [_vModel setModel];
    [_myView showView:_vModel];
}

View.h:

#import <UIKit/UIKit.h>
#import "MyViewModel.h"
#import "FBKVOController.h"
#import "NSObject+FBKVOController.h"

@interface MyView : UIView
@property (nonatomic,strong) UILabel *myLabel;
@property (nonatomic,strong) UIButton *btn;
@property (nonatomic,strong) MyViewModel *VM;
- (void)showView:(MyViewModel *)viewModel;

@end

View.m

#import "MyView.h"

@implementation MyView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 60)];
        _myLabel.backgroundColor = [UIColor greenColor];
        [self addSubview:self.myLabel];
        
        self.btn = [UIButton buttonWithType:UIButtonTypeSystem];
        self.btn.frame = CGRectMake(0, 50, self.bounds.size.width, 60);
        [self.btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
        self.btn.backgroundColor = [UIColor redColor];
        [self.btn setTitle:@"点击" forState:UIControlStateNormal];
        [self addSubview:self.btn];
    }
    return self;
}

- (void)click{
    [self.VM responseClick];
}

- (void)showView:(MyViewModel *)viewModel{
    self.VM = viewModel;
    [self.KVOController observe:viewModel keyPath:@"contentStr" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
        NSLog(@"%@",change[NSKeyValueChangeNewKey]);
        self.myLabel.text = change[NSKeyValueChangeNewKey];
    }];
}


- (void)layoutSubviews{
    [super layoutSubviews];
}
@end

Model.h:

@interface MyModel : NSObject
@property (nonatomic,copy) NSString *title;
@end

ViewModel.h:

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

@interface MyViewModel : NSObject
@property (nonatomic,copy) NSString *contentStr;
- (void)setModel;
- (void)responseClick;
@end

ViewModel.m:

#import "MyViewModel.h"
#import "FBKVOController.h"

@implementation MyViewModel
- (void)setModel{
    MyModel *model = [MyModel new];
    model.title = @"淘宝";
    self.contentStr = model.title;
}

- (void)responseClick{
    NSInteger num = arc4random_uniform(20);
    NSString *str = [NSString stringWithFormat:@"%ld",num];
    self.contentStr = str;
}

@end

猜你喜欢

转载自blog.csdn.net/grl18840839630/article/details/80081346