UITableViewy基本使用小例子

//

//  MJViewController.m

//  01-UITableView01-多组数组展示

//

//  Created by apple on 13-11-28.

//  Copyright (c) 2013年 itcast. All rights reserved.

//

 

#import "MJViewController.h"

#import "Province.h"

 

 

@interface MJViewController () <UITableViewDataSource>

{

    NSArray *_allProvinces; // 所有的省份

}

@end

 

@implementation MJViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    // 1.添加tableView

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];

    tableView.dataSource = self;

    [self.view addSubview:tableView];

    

    // 2.初始化数据

    _allProvinces = @[

        [Province provinceWithHeader:@"广东" footer:@"广东好" cities:@[@"广州", @"深圳"]],

        

        [Province provinceWithHeader:@"湖南" footer:@"湖南也好" cities:@[@"长沙"]],

        

        [Province provinceWithHeader:@"广东2" footer:@"广东好" cities:@[@"广州", @"深圳"]],

        

        [Province provinceWithHeader:@"湖南2" footer:@"湖南也好" cities:@[@"长沙"]]

    ];

}

 

#pragma mark - 数据源方法

#pragma mark 一共有多少组(section == 区域组)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return _allProvinces.count;

}

 

#pragma mark 第section组一共有多少行

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    // 1.取得第section组的省份

    Province *province = _allProvinces[section];

    

    // 2.取得省份里面的城市数组

    return province.citites.count;

}

 

#pragma mark 返回每一行显示的内容(每一行显示怎样的cell)

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

{

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

    

    Province *province = _allProvinces[indexPath.section];

    

    // 展示文字数据

    cell.textLabel.text = province.citites[indexPath.row];

    

    return cell;

}

 

#pragma mark 第section组显示的头部标题

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

//{

//    Province *province = _allProvinces[section];

//    

////    return province.header;

//    return [province header];

//}

 

#pragma mark 第section组显示的尾部标题

//- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

//{

//    return [_allProvinces[section] footer];

//}

 

#pragma mark 返回表格右边的显示的索引条

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

{

    NSMutableArray *titles = [NSMutableArray array];

    

    for (Province *p in _allProvinces) {

        [titles addObject:p.header];

    }

    

    return titles;

}

@end

原文地址:https://www.cnblogs.com/xgj0721/p/4340296.html