AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[MyTableViewController alloc]initWithStyle:UITableViewStyleGrouped]];
[self.window makeKeyAndVisible];
return YES;
}
MyTableViewController.M
#import "MyTableViewController.h"
#import "Data.h"
#import "City.h"
@interface MyTableViewController ()
@property(nonatomic,strong)NSArray *cityDatas;
@end
@implementation MyTableViewController
-(NSArray *)cityDatas {
if (_cityDatas == nil) {
//数组 保存的是 所有城市的数据
_cityDatas = [Data allCities];
}
return _cityDatas;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.cityDatas.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
City *city = self.cityDatas[section];
//城市的 子区域 有个多少个 该城市的分区就应该有多少行
return city.subAreas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"id"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"id"];
}
//把分区对应的 城市对象取出
City *city = self.cityDatas[indexPath.section];
cell.textLabel.text = city.subAreas[indexPath.row];
return cell;
}
City.h
//城市名称
@property(nonatomic,strong)NSString *name;
//子区域
@property(nonatomic,strong)NSArray *subAreas;
//如果 分区头 使用的是 View 的话,必须设置分区头的 高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 44;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//取出 当前 分区 对应的城市对象
City *city = self.cityDatas[section];
UILabel *label = [[UILabel alloc]init];
label.frame = CGRectMake(0, 0, tableView.frame.size.width, 44);
//使用城市的名称 做为 分区头使用
label.text = city.name;
label.textAlignment = NSTextAlignmentCenter;
return label;
}
Data.h
//获取所有城市的数组
+(NSArray*)allCities;
Data.M
+(NSArray *)allCities {
City *beijing = [[City alloc]init];
beijing.name = @"北京";
beijing.subAreas = @[@"东城",@"西城",@"朝阳"];
City *shanghai = [[City alloc]init];
shanghai.name = @"上海";
shanghai.subAreas = @[@"浦东",@"徐汇"];
City *guangdong = [[City alloc]init];
guangdong.name = @"广东";
guangdong.subAreas = @[@"白云",@"越秀",@"东莞"];
City *hubei = [[City alloc]init];
hubei.name = @"湖北";
hubei.subAreas = @[@"武汉",@"十堰",@"天门"];
return @[beijing, shanghai, guangdong, hubei];
}