对于MVVM框架,大家应该并不陌生,如果对这方面还不清楚的,可以去看一下一下三篇文章,应该会有一个比较清楚的认识。
iOS 架构模式--解密 MVC,MVP,MVVM以及VIPER架构
读了这三篇文章,你应该就不会对MVVM陌生了, 我这里算是对以上几篇文章以及个人的理解,上代码展示一下自己认为的MVVM写法,当然:我这里的写法是从唐巧的猿题库里面借鉴过来的,算是对MVVM的一个变种吧。
Talk is cheap, show you the code。
用这个界面来说一下MVVM如何写~
1.M层
#import <Foundation/Foundation.h>
@interface JBSystemMessageModel : NSObject
/** 消息ID */
@property (nonatomic,assign) int messageID;
/** 作者 */
@property (nonatomic,copy) NSString *author;
/** 标题 */
@property (nonatomic,copy) NSString *title;
/** 内容 */
@property (nonatomic,copy) NSString *content;
/** 时间 */
@property (nonatomic,copy) NSString *publishedTime;
/** 是否阅读 */
@property (nonatomic,assign, readonly)BOOL isRead;
@end
2.V层(当然,严格上说Controller也是V层,但我比较喜欢把Controller看成是“502”,也就是把M、V、VM链接在一起然后展示到界面的强力胶,所以这里的V层主要展示SystemMessageCell)
#import <UIKit/UIKit.h>
#import "JBSystemMessageModel.h"
@protocol JBSystemMessageDelegate <NSObject>
@optional
- (void)moreInformation:(JBSystemMessageFrameModel *)frameModel;
@end
@interface JBSystemMessageCell : UITableViewCell
@property (nonatomic,strong) JBSystemMessageFrameModel *frameModel;
@property (nonatomic,weak) id<JBSystemMessageDelegate> delegate;
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
SystemMessageCell.m文件,其实也就是大家常写的控件的创建(单纯的创建,不写任何业务逻辑,最后赋值还是用setFrameModel进行赋值),
@implementation JBSystemMessageCell
+ (instancetype)cellWithTableView:(UITableView *)tableView {
staticNSString *reuseID =@"JBSystemMessageCell";
JBSystemMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
if (!cell) {
cell = [[JBSystemMessageCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:reuseID];
}
return cell;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [superinitWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.backgroundColor =BackgroundColor;
// 点击cell的时候不要变色
self.selectionStyle =UITableViewCellSelectionStyleNone;
// 设置标题cell
[self setUpCell];
}
return self;
}
- (void)setUpCell {
// 创建控件
}
赋值:setFramModel,当然你也可以像猿题库里面那样自己写一个方法进行赋值都是可以的