iOS--UITableViewCell图片的自适应显示

在实际的项目开发过程中,我们经常会遇到图片的处理问题,如果我们的请求结果中包含图片的宽、高,那样处理起来简单很多。一旦请求结果中没有这些信息就显得很操蛋。我们给出一个固定的宽高,又显得展示效果不是那么好。那么只知道图片url的情况下,利用UITableViewCell来显示并进行高度自适应有哪些实现方法呢?
今天我就针对这种情况,把我做知道的两种实现方式:

一、通知####

借助于SDWebImage,其原理很简单,就是在图片显示之后拿到图片的宽高,显示对应图片的cell发送通知,制定对象接受通知后,进行相应的刷新操作。
首先,我们自定义两个类:LGJCellFrameModel和LGJCellModel
LGJCellModel:包含图片的宽,高,URL
LGJCellFrameModel:包含图片的frame,所在cell的高度,LGJCellModel模型对象
其中自定义LGJCellModel的代码:

#import <Foundation/Foundation.h>

@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 <Foundation/Foundation.h>
#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 <UIKit/UIKit.h>
#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:@"img_default@2x.png"] 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;
}

返回行高部分也会相应容易很多,若已计算返回计算好的行高,若无返回默认行高。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,963评论 6 542
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,348评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,083评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,706评论 1 317
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,442评论 6 412
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,802评论 1 328
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,795评论 3 446
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,983评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,542评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,287评论 3 358
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,486评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,030评论 5 363
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,710评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,116评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,412评论 1 294
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,224评论 3 398
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,462评论 2 378

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,170评论 4 61
  • 今天看了篇古典的在专栏里的文章,讲的是关于flow(心流)的概念,发现真的是只有深入一个认知,我们才能懂得背后的意...
    kasitravel阅读 609评论 0 0
  • 我甚至早早穿上了长裤,只是贪恋那多出来的一丝棉料的温暖。 2017年9月22日 星期五 晴 慢慢睁开双眼,没有了酸...
    默默喜欢你阅读 724评论 2 4
  • http://www.cnblogs.com/ZhangRuoXu/p/6367084.html
    嗷嗷嗷喵喵喵阅读 164评论 0 0