2.展示單組數據
展示lol英雄
預先效果:
Snip20160314_5.png
同樣的, 我們需要先設置,三個方法.
注意:
由于我們的是設置單組數據, 所以, 我們實際上是兩種方法, 第一個方法是: 設置一共有多少組, 現在你由于我們確定了只有一組.
注意:
不要忘記了,遵守協議: <UITableViewDataSource, UITableViewDelegate>
1. 材料準備
- 我們需要一個為英雄簡述plist文檔
- 我們需要一些英雄的圖片
2. storyboard設置
storyboard中, 我們要拖入一TableView,然后將其設置為我們控制器的一個方法
3. 代碼書寫
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 97;
}
我們的這個方法, 首先傳出的是一個數據, 等我們將我們的plist文件傳入之后, 我們再重寫代碼,而在以前,我們寫其他的程序的時候, 就有提到過,一旦遇到數據. 我們盡量使用可以代替的變量.
例如, 在這里我們使用的是數據: 97.這個代表的是我們這個展示英雄程序, 一共有97個英雄.
但是, 一旦我們導入了plist文件, 那么我們就可以利用return self.heros.count;
代替
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
heros *hero = self.heros[indexPath.row];
cell.textLabel.text = hero.name;
cell.detailTextLabel.text = hero.intro;
cell.imageView.image = [UIImage imageNamed:hero.icon];
return cell;
}
在這個方法中:
-
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
注意的是這里面cell
的狀態不是先前的的default
了.
而現在這種狀態是效果是, 我們的每一個cell
可以顯示的有: 圖標`cell
名\簡述 - 上面的
cell
的三種方法: textLable之類的, 其實都是由我們的hero這個數組提供的, 另一種說法就是: 都是由我們的plist文件提供的
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) return 100;
return 60;
}
- 這個方法是我們設置每一個
cell
的高度. 這個方法可以隨意設置任意一行的高度 -
self.tableView.rowHeight = 60;
這一行代碼也是設置每一個cell
的高度, 但是這一個與上面的方法區別就是, 這個只可以將每一個cell
設置為一致的高度, 不能單獨設置,任意一行的高度了
至于我們的plist文件的導入 , 在這里,我并不想再說一遍了, 所以我的選擇是直接上代碼:
- (NSArray *)heros
{
if (_heros == nil) {
// 初始化
// 1.獲得plist的全路徑
NSString *path = [[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil];
// 2.加載數組
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
// 3.將dictArray里面的所有字典轉成模型對象,放到新的數組中
NSMutableArray *heroArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.創建模型對象
GJHero *hero = [GJHero heroWithDict:dict];
// 3.2.添加模型對象到數組中
[heroArray addObject:hero];
}
// 4.賦值
_heros = heroArray;
}
return _heros;
}
- 這個是在控制器里寫的代碼, 注意在一開始我們也要創建一個屬性:數組:
@property (nonatomic, strong) NSArray *heros;
- 類外我們要創建一個類, 用來存放我們的數據: (類的名稱就是hero)
這個是.m文件
#import "GJHero.h"
@implementation GJHero
+ (instancetype)heroWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
@end
這個是.h文件
#import <Foundation/Foundation.h>
@interface GJHero : 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