前言
现在市面上有很多app都有联动功能,有的是两个TableView之间的联动,比如美团外卖,百度外卖,饿了么等等。有的是TablView与CollectionView之间的联动,比如礼物说等等。
本文仿造了美团外卖和礼物说,分别实现了两个TableView之间和TablView与CollectionView之间的联动效果,效果图看下面的gif图。
先附上gif图的demo下载链接,【GitHub】、【Code4App】、【OSChina】,简书文章地址,配合demo一起看文章,效果会更佳。
正文
一、TableView与TableView之间的联动
下面来说下实现两个TableView之间联动的主要思路:
先解析数据装入模型,objectWithDictionary:
是将字典转化为模型,这个工具是我用runtime写的,一行代码解析数据,具体使用方法可以参考我简书上另一篇文章【Objective-C中的Runtime】。
NSString *path = [[NSBundle mainBundle] pathForResource:@"meituan" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *foods = dict[@"data"][@"food_spu_tags"];
for (NSDictionary *dict in foods)
{
CategoryModel *model = [CategoryModel objectWithDictionary:dict];
[self.categoryData addObject:model];
NSMutableArray *datas = [NSMutableArray array];
for (FoodModel *f_model in model.spus)
{
[datas addObject:f_model];
}
[self.foodData addObject:datas];
}
定义两个TableView:LeftTableView和RightTableView。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (_leftTableView == tableView)
{
LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Left forIndexPath:indexPath];
FoodModel *model = self.categoryData[indexPath.row];
cell