1.在storyboard里拖2个UITabelView,并把deletegate和dataSoure属性连线到当前控制器。
设置2个tableView的cell的标识。
布局添加约束,2个tableView等高等宽。
//
// ViewController.m
#import "ViewController.h"
#import "CategoryModel.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
/** 左边表格 */
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
/** 右边表格 */
@property (weak, nonatomic) IBOutlet UITableView *subcategoryTableView;
/** 所有的类别数据 */
@property (nonatomic, strong) NSArray *categories;
@end
@implementation ViewController
- (NSArray *)categories
{
if (_categories == nil) {
//这里加载本地plist文件中的数据,实际应该是从服务器端获取数据
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"categories" ofType:@"plist"]];
NSMutableArray *categoryArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
[categoryArray addObject:[CategoryModel categoryWithDict:dict]];
}
_categories = categoryArray;
}
return _categories;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 默认选中左边表格的第0行
[self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
// 设置右边表格的contentInset属性
self.subcategoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// 左边表格
if (tableView == self.categoryTableView) return self.categories.count;
// 右边表格
CategoryModel *model = self.categories[self.categoryTableView.indexPathForSelectedRow.row];
return model.subcategories.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 左边表格
if (tableView == self.categoryTableView) {
static NSString *ID = @"category";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 取出模型
CategoryModel *model = self.categories[indexPath.row];
// 配置cell
cell.imageView.image = [UIImage imageNamed:model.icon];
cell.imageView.highlightedImage = [UIImage imageNamed:model.highlighted_icon];
cell.textLabel.highlightedTextColor = [UIColor redColor];
cell.textLabel.text = model.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
} else {
// 右边表格
static NSString *ID = @"subcategory";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 获得左边表格被选中的模型
CategoryModel *model = self.categories[self.categoryTableView.indexPathForSelectedRow.row];
cell.textLabel.text = model.subcategories[indexPath.row];
return cell;
}
}
#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.categoryTableView) {
[self.subcategoryTableView reloadData];
}
}
@end