原理:处理数据源
1.计算条目一的字符串所占宽度
#import "NSString+Extension.h" //NSString 分类(添加新功能:根据字号计算字符串宽度)
#pragma mark -根据字号来计算字符串的宽度
- (float) widthWithFont: (UIFont *) font{
CGRect textRect = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, font.pointSize) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:font}
context:nil];
return ceil(textRect.size.width);
}
2.加上“ ”中间一段空格的宽度
3.再加上条目二字符串的宽度
4.如果宽度超过屏幕宽度,则将数据换到下一行中(flag = 0;)数据源单条数据从新开始拼接多个条目
-(void)testDealDataSource{
NSArray * dataArray = @[@"全面面包(100g)",@"全面面包(200g)",@"秘制红烧肉(300g)",@"全面面包(400g)",@"蜜汁红烧排骨(500g)"];
// NSArray * dataArray = @[@"面包(100g)",@"面包(200g)",@"红烧肉(300g)",@"全面面包(400g)",@"蜜汁红烧排骨(500g)"];
NSMutableArray * realDataArray = [NSMutableArray array];
NSMutableString * mustr = [NSMutableString string];
NSInteger flag = 0;
NSString * intervalStr = @" ";
CGFloat interval = [intervalStr widthWithFont:[UIFont systemFontOfSize:13]];
for(int i = 0; i < dataArray.count; i++){
NSString * sr = dataArray[i];
CGFloat width = [sr widthWithFont:[UIFont systemFontOfSize:13]];
CGFloat widthTotal = [mustr widthWithFont:[UIFont systemFontOfSize:13]];
if(JYEScreenWidth - (width + interval + widthTotal) > 0.001 && flag <= 2){
if(i != 0){
[mustr appendString:intervalStr];
}
flag ++;
[mustr appendString:sr];
}else{
flag = 0;
[realDataArray addObject:mustr];
mustr = [NSMutableString string];
[mustr appendString:sr];
}
if(i == dataArray.count - 1){
[realDataArray addObject:mustr];
}
}
self.dataSourceArray = realDataArray;
[self.tableView reloadData];
for(NSString * object in realDataArray){
NSLog(@"%@",object);
}
}