IOS第七天(2:UiTableView 加上数据分离)

****加上数据分离

#import "HMViewController.h"
#import "HMStudent.h"

@interface HMViewController () <UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 数据列表 */
@property (nonatomic, strong) NSArray *dataList;
@end

@implementation HMViewController

- (NSArray *)dataList
{
    if (_dataList == nil) {
        HMStudent *stu1 = [[HMStudent alloc] init];
        stu1.title = @"黑马1期";
        stu1.desc = @"牛叉";
        
        // 生成编号数组
        NSMutableArray *arrayM1 = [NSMutableArray array];
        for (int i = 0; i < 10; i++) {
            [arrayM1 addObject:[NSString stringWithFormat:@"%@ - %04d", stu1.title, i]];
        }
        stu1.students = arrayM1;
        
        HMStudent *stu2 = [[HMStudent alloc] init];
        stu2.title = @"黑马2期";
        stu2.desc = @"也牛叉";
        
        // 生成编号数组
        NSMutableArray *arrayM2 = [NSMutableArray array];
        for (int i = 0; i < 20; i++) {
            [arrayM2 addObject:[NSString stringWithFormat:@"%@ - %04d", stu2.title, i]];
        }
        stu2.students = arrayM2;
        
        _dataList = @[stu2, stu1];
    }
    return _dataList;
}

#pragma mark - 数据源方法
// 如果没有实现,默认是1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataList.count;
}

// 每个分组中的数据总数
// sction:分组的编号
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // students数组中的元素数量
    // 取出数组中对应的学员信息
//    HMStudent *stu = self.dataList[section];
//    return stu.students.count;
    // 计算数量的代码,由于层次比较深,建议使用上面的代码
    return [[self.dataList[section] students] count];
}

// 告诉表格控件,每一行cell单元格的细节
// indexPath
//  @property(nonatomic,readonly) NSInteger section;    分组
//  @property(nonatomic,readonly) NSInteger row;        行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 实例化TableViewCell时,使用initWithStyle方法来进行实例化
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    // 取出indexPath对应的数据
    HMStudent *stu = self.dataList[indexPath.section];
    
    cell.textLabel.text = stu.students[indexPath.row];
    
    return cell;
}

// 返回分组的标题文字
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//    HMStudent *stu = self.dataList[section];
//    return stu.title;
    return [self.dataList[section] title];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
//    HMStudent *stu = self.dataList[section];
//    return stu.desc;
    // 直接从数组中取出的对象是id类型,因为没有明确的类型,因此不能使用.语法,只能使用getter方法
    return [self.dataList[section] desc];
}

@end

 

posted @ 2015-08-04 11:18  iso  阅读(201)  评论(0编辑  收藏  举报