在实际的项目开发过程中,我们经常会遇到图片的处理问题,如果我们的请求结果中包含图片的宽、高,那样处理起来简单很多。一旦请求结果中没有这些信息就显得很操蛋。我们给出一个固定的宽高,又显得展示效果不是那么好。那么只知道图片url的情况下,利用UITableViewCell来显示并进行高度自适应有哪些实现方法呢?
今天我就针对这种情况,把我做知道的两种实现方式:
一、通知####
借助于SDWebImage,其原理很简单,就是在图片显示之后拿到图片的宽高,显示对应图片的cell发送通知,制定对象接受通知后,进行相应的刷新操作。
首先,我们自定义两个类:LGJCellFrameModel和LGJCellModel
LGJCellModel:包含图片的宽,高,URL
LGJCellFrameModel:包含图片的frame,所在cell的高度,LGJCellModel模型对象
其中自定义LGJCellModel的代码:
#import
@interface LGJCellModel : NSObject
@property (nonatomic ,copy) NSString *url;
@property (nonatomic ,copy) NSString *picW;
@property (nonatomic ,copy) NSString *picH;
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)modelWithDict:(NSDictionary *)dict;
@end
#import "LGJCellModel.h"
@implementation LGJCellModel
-(instancetype)initWithDict:(NSDictionary *)dict
{
if (self=[super init]) {
[self setValuesForKeysWithDictionary:dict];
if (self.url) {
[self setValue:[NSString stringWithFormat:@"%.0f",kScreenWidth - 20] forKey:@"picW"];
[self setValue:@"44" forKey:@"picH"];
}
}
return self;
}
+(instancetype)modelWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
@end
LGJCellFrameModel的自定义
#import
#import "LGJCellModel.h"
@interface LGJCellFrameModel : NSObject
@property (nonatomic,assign,readonly) CGRect pictureF;
@property (nonatomic,assign,readonly) CGFloat cellHeight;
@property (nonatomic,strong) LGJCellModel *cellModel;
@end
#import "LGJCellFrameModel.h"
#import "LGJCellModel.h"
@implementation LGJCellFrameModel
-(void)setCellModel:(LGJCellModel *)cellModel
{
_cellModel=cellModel;
if (self.cellModel.url) {
CGFloat pictureX=10;
CGFloat pictureY=10;
CGFloat pictureW=[self.cellModel.picW floatValue];
CGFloat pictureH=[self.cellModel.picH floatValue];
_pictureF=CGRectMake(pictureX, pictureY, pictureW, pictureH);
_cellHeight=CGRectGetMaxY(_pictureF);
}
else
{
_cellHeight = 0;
}
}
@end
接下来,我们自定义UITableViewCell
#import
#import "LGJCellFrameModel.h"
@interface LGJCell : UITableViewCell
@property (nonatomic,strong) LGJCellFrameModel *modelFrame;
-(void)showCellWithModel:(LGJCellFrameModel *)frameModel indexPath:(NSIndexPath *)indexPath;
@end
#import "LGJCell.h"
#import "LGJCellFrameModel.h"
#import "LGJCellModel.h"
@interface LGJCell ()
@property (nonatomic,strong) UIImageView *pictureView;
@end
@implementation LGJCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.pictureView=[[UIImageView alloc] init];
[self.contentView addSubview:self.pictureView];
}
return self;
}
-(void)showCellWithModel:(LGJCellFrameModel *)frameModel indexPath:(NSIndexPath *)indexPath
{
_modelFrame = frameModel;
[self settingData:(NSIndexPath *)indexPath];
[self settingFrame];
}
-(void)settingData:(NSIndexPath *)tager
{
LGJCellModel *model=self.modelFrame.cellModel;
if (model.url) {
self.pictureView.hidden=NO;
NSString *imageUrl=[NSString stringWithFormat:@"%@",model.url];
[self.pictureView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"[email protected]"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if ([model.picH isEqualToString:@"44"]) {
NSDictionary *userInfo = @{@"Height" : @(image.size.height*(kScreenWidth-20)/image.size.width),@"indexPath":tager};
[[NSNotificationCenter defaultCenter] postNotificationName:@"SelectionViewController" object:nil userInfo:userInfo];
}
}];
}
else
{
self.pictureView.hidden=YES;
}
}
-(void)settingFrame
{
if (self.modelFrame.cellModel.url) {
self.pictureView.frame=self.modelFrame.pictureF;
}
}
@end
我们在UITableView的dataSource方法- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中执行:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *ID=@"cellLGJCell";
LGJCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell=[[LGJCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
else
{
for (UIView *sub in cell.contentView.subviews) {
if ([sub isKindOfClass:[UIImageView class]]) {
UIImageView *tempImageView= (UIImageView *)sub;
tempImageView.image=nil;
}
if ([sub isKindOfClass:[UILabel class]]) {
UILabel *tempUILabel= (UILabel *)sub;
tempUILabel.text=nil;
}
}
}
[cell showCellWithModel:self.cellFrames[indexPath.row] indexPath:indexPath];
cell.userInteractionEnabled = YES;
return cell;
}
并且在对应控制器中注册通知,并实现刷新方法reloadCell:
[[GerneralTool alloc]addObserverWithNames:@[@"SelectionViewController"] selectors:@[@"reloadCell:"] observer:self objects:nil];
-(void)addObserverWithNames:(NSArray *)names selectors:(NSArray *)selectors observer:(id)observer objects:(NSArray *)objects{
for (int index = 0; index < names.count; index++) {
NSString *str = selectors[index];
SEL sel = NSSelectorFromString(str);
[[NSNotificationCenter defaultCenter] addObserver:observer selector:sel name:names[index] object:objects[index]];
}
}
- (void)reloadCell:(NSNotification *)info
{
NSDictionary *dict=info.userInfo;
NSString *picHeight=[[dict objectForKey:@"Height"] stringValue];
NSIndexPath *indexpath=[dict objectForKey:@"indexPath"];
if ( self.cellFrames.count>=indexpath.row) {
LGJCellFrameModel *modelFrame=[self.cellFrames objectAtIndex:indexpath.row];
modelFrame.cellModel.picH=picHeight;
modelFrame.cellModel=modelFrame.cellModel;
[self.cellFrames replaceObjectAtIndex:indexpath.row withObject:modelFrame];
[self.detailView.tableView reloadData];
}
}
在对应的返回高度的方法中
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
LGJCellFrameModel *cellFrame = self.cellFrames[indexPath.row];
return cellFrame.cellHeight;
}
二、先下载,后显示####
这里我们需要使用到SDWebImage中SDWebImageDownloader与SDImageCache这两个类来实现功能,分别为图片下载类于图片缓存类。具体代码如下,假设以获取所需图片网址数组为_picArr。
首先借助SDImageCache进行判断对应图片是否缓存。若已缓存,获取其真实需要显示高度(当前屏幕宽度乘图片比例即可),将获取到的高度存入高度字典中。若不存在缓存,使用SDWebImageDownloader进行下载,在下载结束后同样计算高度并缓存图片。SDWebImageDownloader下载图片为异步,无法保证图片按顺序下载完成,因此这里使用字典存储而非数组。字典键值对存储的即为所对应行应显示的高度。
for (NSInteger i = 0; i < _picArr.count; i++) {
//获取图片网址
NSString *picUrl = _picArr[i];
//根据图片网址获取缓存
UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:picUrl];
if (cachedImage) {//若存在 计算图片真实需要显示高度 存入字典
CGFloat height = cachedImage.size.height * self.view.bounds.size.width / cachedImage.size.width;
[_rowHeightDict setObject:[NSNumber numberWithFloat:height] forKey:[NSNumber numberWithInteger:i]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
} else {//不存在缓存 使用SDWebImageDownloader下载
[[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:picUrl] options:SDWebImageDownloaderProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
} completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (finished) {
//对现在图片进行缓存
[[SDImageCache sharedImageCache] storeImage:image forKey:picUrl toDisk:YES];
CGFloat height = image.size.height * self.view.bounds.size.width / image.size.width;
[_rowHeightDict setObject:[NSNumber numberWithFloat:height] forKey:[NSNumber numberWithInteger:i]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
}
}
当前显示的行数需返回行高字典的键值对个数。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _rowHeightDict.count;
}
若图片已缓存,加载缓存图片,若无缓存,显示默认placehold图片。
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableID];
UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:_picArr[indexPath.row]];
if (!image) {
cell.photoImageView.image = [UIImage imageNamed:@"placehold"];
} else {
cell.photoImageView.image = image;
}
return cell;
}
返回行高部分也会相应容易很多,若已计算返回计算好的行高,若无返回默认行高。