首页 > 代码库 > 开发进阶18_通过xib自定义Cell
开发进阶18_通过xib自定义Cell
UITableViewController
{
}
UINib *nib = [UINib nibWithNibName:@"NewsCell" bundle:nil];
NSArray *objects = [nib instantiateWithOwner:nil options:nil];
@interface NewsCellController ()
{
NSMutableArray *_allNews;
}
@end
@implementation NewsCellController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.rowHeight = [NewCell rowHeight];
//从plist文件中取出数据
NSArray *arr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"news.plist" ofType:nil]];
_allNews = [NSMutableArray array];
for (NSMutableArray *dict in arr){
[_allNews addObject:[NewsModel newsWithDict:dict]];
}
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _allNews.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NewCell ID]];
if(cell == nil){
cell = [NewCell newCell];
}
//传递数据模型
cell.newsModel = _allNews[indexPath.row];
return cell;
}
@end
#import "NewCell.h"
#import "NewsModel.h"
@implementation NewCell
+ (CGFloat)rowHeight
{
return 80;
}
+ (NSString *)ID
{
return @"cell";
}
+ (id)newCell
{
return [[NSBundle mainBundle] loadNibNamed:@"NewCell" owner:nil options:nil][0];
}
- (void)setNewsModel:(NewsModel *)newsModel
{
_newsModel = newsModel;
_titleLabel.text = newsModel.title;
_authorLabel.text = [NSString stringWithFormat:@"作者:%@", newsModel.author];
_commentsLabel.text = [NSString stringWithFormat:@"评论:%d",newsModel.comments];
_cellView.image = [UIImage imageNamed:newsModel.cellView];
}
@end
@interface NewsModel : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *author;
@property (nonatomic, assign) int comments;
@property (nonatomic, copy) NSString *cellView;
+ (id)newsWithDict:(NSDictionary *)dict;
- (id)initWithDict:(NSDictionary *)dict;
@end
@implementation NewsModel
+ (id)newsWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (id)initWithDict:(NSDictionary *)dict
{
if(self = [super init]){
self.title = dict[@"title"];
self.author = dict[@"author"];
self.cellView = dict[@"icon"];
self.comments = [dict[@"comments"] intValue];
}
return self;
}
@end
开发进阶18_通过xib自定义Cell