項目中頁面須要用到一個展現多個網絡圖片的頁面,圖片高低不等.異步加載完成時間不一樣,不能將高度固定,該文章用於簡單佈局.數組
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.將改變高度的方法另行封裝,上文中調用code
#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給頁面固定高度.(每一個佔位圖也能夠使用轉圈的加載動畫).it
圖片異步加載過程當中,哪一個圖片先加載完畢就修正imgView的高度和位置.還沒有加載完畢就顯示佔位圖但不錯位.io
最終加載完畢圖片寬度一致,上下間距一致且不被拉伸變形.