UITableVIew程序员iOS Developer

UI之 06 TableView 02 单组数据展示(lol英雄

2016-03-15  本文已影响211人  高俊

2.展示单组数据

展示lol英雄

预先效果:

Snip20160314_5.png

同样的, 我们需要先设置,三个方法.

注意:由于我们的是设置单组数据, 所以, 我们实际上是两种方法, 第一个方法是: 设置一共有多少组, 现在你由于我们确定了只有一组.

注意:不要忘记了,遵守协议: <UITableViewDataSource, UITableViewDelegate>

1. 材料准备

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;
}

在这个方法中:


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) return 100;
    return 60;
}

至于我们的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;
}

这个是.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
上一篇下一篇

猜你喜欢

热点阅读