您的位置:首页 > 移动开发 > IOS开发

[iOS开发项目-11] 英雄列表

2015-11-07 22:58 393 查看
本项目是取自传智播客的教学项目,加入笔者的修改和润饰。

1. 项目名称:英雄列表

2. 项目截图展示



3. 项目功能

单纯显示英雄数据

4. 项目代码

VC.m

#import "ViewController.h"
#import "SJHero.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSArray *heros;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.tableView.dataSource = self;
self.tableView.delegate = self;
}

- (NSArray *)heros
{
if (_heros == nil) {

NSString *path = [[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil];

NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];

//新建模型数组
NSMutableArray *heroArray = [NSMutableArray array];

//遍历dictArray数组
for (NSDictionary *dict in dictArray) {

// 3.1.创建模型对象
SJHero *hero = [SJHero heroWithDict:dict];

// 3.2.添加模型对象到数组中
[heroArray addObject:hero];
}

_heros = heroArray;

}
return _heros;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.heros.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

SJHero *hero = self.heros[indexPath.row];

cell.textLabel.text =hero.name;
cell.detailTextLabel.text = hero.intro;
cell.imageView.image = [UIImage imageNamed:hero.icon];

return cell;
}

#pragma mark - 代理方法

//每一行的高度不一致的时候使用这个方法来设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) return 50;
return 50;
}

@end


模型类.h

#import <Foundation/Foundation.h>

@interface SJHero : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *intro;

+ (instancetype) heroWithDict:(NSDictionary *)dict;
- (instancetype) initWithDict:(NSDictionary *)dict;

@end


模型类.m

#import "SJHero.h"

@implementation SJHero

+ (instancetype) heroWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}

- (instancetype) initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {

[self setValuesForKeysWithDictionary:dict];
}

return self;
}

@end


5. 本项目必须掌握的代码段

在cell内部设置

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

SJHero *hero = self.heros[indexPath.row];

cell.textLabel.text =hero.name;
cell.detailTextLabel.text = hero.intro;
cell.imageView.image = [UIImage imageNamed:hero.icon];

return cell;
}


6. 笔记

数据源

UITableView需要一个数据源(dataSource)来显示数据,没有设置数据源的UITableView只是个空壳

UITableView会向数据源查询一共有多少行数据以及每一行显示什么数据等

凡是遵守UITableViewDataSource协议的OC对象,都可以是UITableView的数据源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: