IOS第七天(5:UiTableView 汽车品牌,复杂模型分组展示,A-Z索要列表) (2015-08-05 14:03)

时间:2023-03-08 16:44:26

复杂模型分组展示

#import "HMViewController.h"
#import "HMCarGroup.h"
#import "HMCar.h" @interface HMViewController () <UITableViewDataSource>
@property (nonatomic, strong) NSArray *carGroups;
@property (nonatomic, strong) UITableView *tableView;
@end @implementation HMViewController - (UITableView *)tableView
{
if (_tableView == nil) {
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView.dataSource = self; [self.view addSubview:_tableView];
}
return _tableView;
} - (NSArray *)carGroups
{
if (_carGroups == nil) {
_carGroups = [HMCarGroup carGroups];
}
return _carGroups;
} - (void)viewDidLoad
{
[super viewDidLoad]; // 调用tableView添加到视图
[self tableView];
} #pragma mark - 数据源方法
// 分组总数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.carGroups.count;
} // 每一组的总数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
HMCarGroup *group = self.carGroups[section]; return group.cars.count;
} // 单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 可重用标示符
static NSString *ID = @"Cell"; // 让表格缓冲区查找可重用cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 如果没有找到可重用cell
if (cell == nil) {
// 实例化cell
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
} // 设置cell内容
// 1> 取出数据模型
HMCarGroup *group = self.carGroups[indexPath.section];
HMCar *car = group.cars[indexPath.row]; // 2> 设置数据
cell.imageView.image = [UIImage imageNamed:car.icon];
cell.textLabel.text = car.name; return cell;
} // 标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// 找到group
HMCarGroup *group = self.carGroups[section]; return group.title;
} // 右侧索引列表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
// 索引数组中的"内容",跟分组无关
// 索引数组中的下标,对应的是分组的下标
// return @[@"哇哈哈", @"hello", @"哇哈哈", @"hello", @"哇哈哈", @"hello", @"哇哈哈", @"hello"]; // 返回self.carGroup中title的数组
// NSMutableArray *arrayM = [NSMutableArray array];
// for (HMCarGroup *group in self.carGroups) {
// [arrayM addObject:group.title];
// }
// return arrayM; // KVC是cocoa的大招
// 用来间接获取或者修改对象属性的方式
// 使用KVC在获取数值时,如果指定对象不包含keyPath的"键名",会自动进入对象的内部查找
// 如果取值的对象是一个数组,同样返回一个数组
NSArray *array = [self.carGroups valueForKeyPath:@"cars.name"];
NSLog(@"%@", array); return [self.carGroups valueForKeyPath:@"title"];
} @end