小红书分类菜单的实现
写在前面的话
这是当初学习iOS开发时做的一个小Demo,写了点笔记没有上传,现在放上来记录一下,现在看当时真的很傻。
实现思路
1.UITableView + UICollectionView布局 左边为UITableView 右边为UICollectionView
2.通过JSONModel读取数据从json文件读取数据 保存到自定义的model
3.点击左侧UITableView的cell时 触发UITableView的didSelectRowAtIndexPath代理方法 然后改变collectionView的数据源
实现效果
实现步骤
1.用JSONModel读取本地json数据
2.tableView + collectionView布局
3.利用tableviewcell的点击方法改变collectionView的数据源
4.使用SDWebImage加载 cell中图片数据
JSONModel
用法:新建自己的model类文件继承 JSONModel
model类文件结构应与json文件结构保持一致
- (void)requestData {
//路径
NSString *path=[[NSBundle mainBundle] pathForResource:@"小红书data" ofType:@"json"];
//数据
NSData *data = [NSData dataWithContentsOfFile:path];
//设置model文件
self.dataModel = [[DataModel alloc] initWithData:data error:nil];
self.tableViewCellModel = self.dataModel.data[0];
NSLog(@"%@",self.dataModel);
[_tableView reloadData];
}
SDWebImage
这里只用了 UIImageView+WebCache
使用 SDWebImage 异步设置图片
NSURL *url = [NSURL URLWithString:dataModel.image];
//使用SDWebImage异步加载图片 加快速度
[_itemImage sd_setImageWithURL:url];
TableViewCell点击改变数据源
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.tableViewCellModel = self.dataModel.data[indexPath.row];
[_collectionView reloadData];
}
这里应该有更好的写法 VC持有了太多模型对象 不太好
难点
-
点击tableViewCell改变 colletionView数据源
遇见的问题:怎么通过选中cell不同改变colletionView的内容
解决办法:在didSelectRowAtIndexPath中修改模型 然后调用collectionView的 reloadData方法
-
遇见的问题:加载很卡
原因: 最开始使用 [UIImage imageWithData:[NSData dataWithContentsOfURL: url]] 方法 这个方法是同步的,图像读取完毕才开始更新视图 ,所以会有卡顿
解决方法:使用SDWebImage异步加载 解决卡顿问题。
字典的读取问题 dictionaryWithContentsOfFile返回Nil而不是NSdictionary
怎么遇见的问题: 使用NSData 的 dataWithContentsOfFile 方法可以读取到json文件 而字典的dictionaryWithContentsOfFile 却返回的是Nil而不是NSdictionary
原因:(id)dictionaryWithContentsOfFile:(NSString *)path参数path完整路径名或相对路径名 . 由path标识的文件必须包含属性列表的字符串表示形式,其根对象是字典 . 返回值包含路径中字典的新字典,如果存在文件错误或文件内容是字典的无效表示,则为nil . (简而言之 ,只能使用plist文件而不是.json创建字典 )
解决方法:1. Data 的dataWithContentsOfFile 方法
2.使用NSJSONSerialization 从文件中获取 json 数据
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Dict" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *dic1 = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil] mutableCopy];
-
更改Cell的选中样式
原因:cell选中时的样式应与背景颜色一致
解决办法:取消选中样式 在cell里面重写
cell.selectionStyle = UITableViewCellAccessoryNone;
//在自定义cell中
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if (selected == YES) {
// 选中时候的样式
self.backgroundColor = RGBColorMake(242, 245, 249, 1);
} else {
// 未选择时的样式
self.backgroundColor = [UIColor whiteColor];
}
}