1、研究背景
之前做的项目因为数据量较小,cell内容不复杂(没有下载图片),cell基本上每一行都使用独立id,加之比较懒,不遵循MVC设计模式,基本上一个TableviewController 全部搞定
- (UITableViewCell *)badUseCellOnTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellID = [NSString stringWithFormat:@"%li_%li",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[cell.contentView addSubview:<#(nonnull UIView *)#>];
return cell;
}
界面稍一复杂,[cell.contentView addSubview:]一堆,而且总是将cell.contentView上的子视图移除,非常不堪
2、模型设计
1、model
模型用来存储数据,造一个init方法,这样可以直接传进来取到的网络数据
MyModel.h
#import <Foundation/Foundation.h>
@interface MyModel : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subTitle;
@property (nonatomic, copy) NSString *imageName;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
MyModel.m
#import "MyModel.h"
@implementation MyModel
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
self.title = dict[@"title"];
self.subTitle = dict[@"subtitle"];
self.imageName = dict[@"imageName"];
}
return self;
}
2、view-cell
自定义cell,引入模型,使用setModel方法获取到需要展示的数据,至于cell的内容,绘制的地方值得探讨:init setModel drawRect。
init及drawRect,在复用成功后,便不再执行,而drawRect每次展示新cell都会执行,若图省事只写一个setModel方法,控件都放在这里初始化,绘制,则必须要在为cell.model赋值前,清空contentView,消耗内存,不推荐。
个人觉得直接在drawRect里初始化控件,使用setModel得到的模型赋值,绘制最佳
Mycell.h
#import <UIKit/UIKit.h>
@class MyModel;
@interface Mycell : UITableViewCell
@property (nonatomic,strong) MyModel *model;
@end
Mycell.m
#import "Mycell.h"
#import "MyModel.h"
@implementation Mycell
- (void)setModel:(MyModel *)model
{
_model = model;
}
- (void)drawRect:(CGRect)rect
{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 80, 80)];
UIImage *image = [UIImage imageNamed:_model.imageName];
[imageView setImage:image];
imageView.contentMode = UIViewContentModeScaleAspectFill;
[self.contentView addSubview:imageView];
UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame), 10, 150, 30)];
titleLabel.text = _model.title;
[self.contentView addSubview:titleLabel];
UILabel *subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame), CGRectGetMaxY(titleLabel.frame)+5, 150, 30)];
subTitleLabel.text = _model.subTitle;
[self.contentView addSubview:subTitleLabel];
}
3、controller - 关键函数
- (UITableViewCell *)reuseCellOnTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"cellID";
Mycell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[Mycell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.model = itemsArray[indexPath.row];
return cell;
}
接下来会研究优化的问题