最近在做商城,做到分类觉得网上应该一大把现成的代码。搜了一会没有搜到,懒人也懒不了了。
写了一会感觉还是有点需要思考的,写下思路和贴上代码,可以参考下。
最后作品:
类似QQ分组列表怎么做就不说。我把子分类和三级分类放到一个cell里了,所以核心代码都在
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath这个方法里面
代码如下
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * cellId = @"categoryCellId";
UITableViewCell * cell;
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}else{
cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
}
NSDictionary * headDic = self.dataSource[indexPath.section];
NSArray * headSubArray = headDic[@"subs"];
NSDictionary * subDic = headSubArray[indexPath.row];
UILabel * subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, ScreenWidth-20, 40)];
subTitleLabel.font = [UIFont systemFontOfSize:15];
subTitleLabel.text = subDic[@"title_zh"];
[cell.contentView addSubview:subTitleLabel];
NSArray * subArray = subDic[@"subs"];
CGFloat sumWidth = 0.0f;
NSInteger row=0;
for (int i=0; i<subArray.count; i++) {
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGSize boundSize = CGSizeMake(ScreenWidth, CGFLOAT_MAX);
CGRect requiredSize = [subArray[i][@"title_zh"] boundingRectWithSize:boundSize options:options attributes:attribute context:nil];
UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(30+sumWidth,40+row*30, requiredSize.size.width, 20)];
[btn setTitle:subArray[i][@"title_zh"] forState:UIControlStateNormal];
[btn setTitleColor:UIColorFromRGB(0xf6f6f6) forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor lightGrayColor]];
btn.layer.cornerRadius = 5;
btn.titleLabel.font = [UIFont systemFontOfSize:11];
[cell.contentView addSubview:btn];
if ((btn.frame.origin.x+btn.frame.size.width)>ScreenWidth) {//当遇到最后一个很长的话需判断是否越过屏幕,如果越过换行
row+=1;
btn.frame = CGRectMake(30,40+row*30, requiredSize.size.width, 20);
sumWidth = requiredSize.size.width+5;
}else{
sumWidth = requiredSize.size.width+sumWidth+5;
if (sumWidth+60>=ScreenWidth) {//如果大于当前屏幕宽度,记录并清零统计宽度
ZYLog(@"sumWidth:%f,scr:%f",sumWidth,ScreenWidth)
row +=1;
sumWidth = 0.0f;
}
}
}
CGRect rect = cell.frame;
rect.size.height = 50+10+row*30;
cell.frame = rect;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
难点和思路:
难点:1.获取的最小一级的分类在按钮上自适应
2.什么时候换行需要判断
3.高度自适应
解决思路:
取三级分类的标题叠加,如果越界就换行。