项目中页面需要用到一个展示多个网络图片的页面,图片高低不等.异步加载完成时间不同,不能将高度固定,该文章用于简单布局.
1.创建用于存放imgView的view
_headerImgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [DMDevceManager screenWidth], 0)]; _headerImgView.backgroundColor = [UIColor whiteColor]; _headerImgView.userInteractionEnabled = YES;
2.创建一个数组用来存放图片高度(按位存放,最多十张)
tmpHeightArr = [NSMutableArray arrayWithArray:@[@0,@0,@0,@0,@0,@0,@0,@0,@0,@0]];
3.每张图片先给定400高度加上占位图告诉用户图片正在加载.(_imgViewHeight是整个大的View的高度)
_imgViewHeight = 40 + (300+5) * _model.imagesArray.count;
4.使用循环创建图片的imgView.(使用tag值标记每个view,方便取出改高度)
for (int i = 0 ;i < _model.imagesArray.count ; i++) { UIImageView * imgView = [[UIImageView alloc]init]; imgView.contentMode = UIViewContentModeScaleAspectFill; imgView.frame = CGRectMake(10, 45 + 300*i, [DMDevceManager screenWidth] - 20, 300); imgView.tag = i + 10000; NSLog(@"%ld",imgView.tag); imgView.image = [UIImage imageNamed:@"pic_11"]; [_headerImgView addSubview:imgView]; }
5.使用SDImage来缓存图片真实高度存进数组
for (int i = 0 ;i < _model.imagesArray.count ; i++) { UIImageView * imgView = (UIImageView *)[_headerImgView viewWithTag:10000 + i]; [imgView sd_setImageWithURL:_model.imagesArray[i] placeholderImage:[UIImage imageNamed:@"pic_11"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (image.size.width >0) { CGFloat height = ([DMDevceManager screenWidth] - 20)/(image.size.width/image.size.height); [tmpHeightArr replaceObjectAtIndex:i withObject:@(height)]; [self createImgs]; } }]; }
6.将改变高度的方法另行封装,上文中调用
#pragma mark - createImg - (void)createImgs { for (int i = 0; i < _model.imagesArray.count ; i ++) { UIImageView * imgView = (UIImageView *)[_headerImgView viewWithTag:10000 + i]; if([tmpHeightArr[i] integerValue]>0) { imgView.height = [tmpHeightArr[i] floatValue]; } for (int j = i+1;j < _model.imagesArray.count+1 ; j++ ) { UIImageView * tmpImgView = (UIImageView *)[_headerImgView viewWithTag:10000 + j]; tmpImgView.y = imgView.bottomY + 5; } if (i == _model.imagesArray.count - 1) { _imgViewHeight = imgView.bottomY; } } [_tableView reloadData]; }
没有使用Coretext图文混排;
实现的效果是进入页面,model传进一个images URL的数组,先使用按数组count给页面固定高度.(每个占位图也可以使用转圈的加载动画).
图片异步加载过程中,哪个图片先加载完毕就修正imgView的高度和位置.尚未加载完毕就显示占位图但不错位.
最终加载完毕图片宽度一致,上下间距一致且不被拉伸变形.