采用MVC設計模式
1.Model層設計
新建CJActive文件
CJActive.h文件中
@interface CJActive : NSObject
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *name;
-(instancetype)initWithDic:(NSDictionary *)dic;
+(instancetype)acitveWithDic:(NSDictionary *)dic;
+(NSMutableArray *)activeList;
@end
CJActive.m文件
-(instancetype)initWithDic:(NSDictionary *)dic{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dic];
}
return self;
}
+(instancetype)acitveWithDic:(NSDictionary *)dic{
return [[self alloc]initWithDic:dic];
}
+(NSMutableArray *)activeList{
NSArray *dicArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]];
//字典轉模型
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dic in dicArray) {
CJActive *active = [CJActive acitveWithDic:dic];
[arrayM addObject:active];
}
return arrayM;
}
2.View層設計
新建CJActiveCell類文件,帶xib的。
CJActiveCell.h文件中
@class CJActive;
@interface CJActiveCell : UITableViewCell
@property (nonatomic, strong) CJActive *getData;//定義一個接口,獲得數據
+(instancetype) cellWithTableView:(UITableView *)tableView;
@end
CJActiveCell.xib文件中進行自定義cell設計
并且子控件關聯至CJActiveCell.m中
@interface CJActiveCell()
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UILabel *title;
@end
在CJActiveCell.m中實現兩個方法
//創建cell
+(instancetype)cellWithTableView:(UITableView *)tableView{
static NSString *reuseID= @"activeCell";
//1.創建可重用的cell
CJActiveCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
//2.判斷為空,一開始初始化
if (cell == nil) {
cell = [[[NSBundle mainBundle]loadNibNamed:@"CJActiveCell" owner:nil options:nil]lastObject];
}
//3.返回
return cell;
}
//重寫getData屬性的setter方法,當getData被賦值的時候,就會調用setter方法,
//在方法里面對cell的內容進行設置,也就是一拿到數據,就設置值
-(void)setGetData:(CJActive *)getData{
_getData = getData;
self.title.text =getData.name;
//.......
} ];
}
3.Controller層設計
CJActiveController.m文件實現
@interface CJActiveController ()<UITableViewDataSource>
@property (nonatomic, strong) NSArray *activeInfo;//定義一個屬性,加載數據
@end
@implementation CJActiveController
//懶加載需要的數據
-(NSArray *)activeInfo{
if (_activeInfo==nil) {
_activeInfo = [CJActive activeList];
}
return _activeInfo;
}
#pragma mark 數據源方法
-(NSInteger)numberOfSectionsInTableView:(nonnull UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.activeInfo.count;
}
-(UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
//1.創建可重用的自定義cell
CJActiveCell *cell =[CJActiveCell cellWithTableView:tableView];
//2.設置值
CJActive *active = self.activeInfo[indexPath.row];
cell.getData =active;
//3.return
return cell;
}