iOS tableView图片未知宽高加载优化 之 runloop

前言

demo: https://github.com/1872784520/ZLMTableViewOptimize
最近项目中经常遇到后台返回图片不给宽高。自己还不能去截取图片尺寸,还要求图片正常显示不要变形。
先说下思路吧:
难点: 1 图片不下来 你就拿不到宽高
2. tableview加载要预先给定高度(说什么用自动布局之类的我就不发表意见了)
解决:1. 图片未下来之前给出一个固定高度
2.图片下来之后计算出宽高然后重刷cell
3.这里冲刷的时候屏幕会一闪一闪的用户看起来会很不爽,需要用到 runloop来解决

#import "MomentViewController.h"
#import "MomentTableViewCell.h"

#import "MomentModel.h"


typedef void(^SaveFuncBlock)(void);

@interface MomentViewController ()
{
    NSInteger cellNum;
    
}

//存放任务的数组
@property (nonatomic, strong) NSMutableArray *saveTaskMarr;

//最大任务数(超过最大任务数的任务就停止执行)
@property (nonatomic, assign) NSInteger maxTasksNumber;

//任务执行的代码块
@property (nonatomic, copy) SaveFuncBlock saveFuncBlock;



@end

@implementation MomentViewController
static NSString * const kCellIdentifier = @"MomentTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UINib *nibCell = [UINib nibWithNibName:NSStringFromClass([MomentTableViewCell class]) bundle:nil];
    [self.tableView registerNib:nibCell forCellReuseIdentifier:kCellIdentifier];
    
    // Do any additional setup after loading the view.
}

- (void)initData
{
    
    _saveTaskMarr = [NSMutableArray array];
    self.maxTasksNumber = 18;
    
    for (NSInteger i = 0 ; i< 1000 ; i++) {
        MomentModel *model = [[MomentModel alloc] init];
        model.name = [NSString stringWithFormat:@"赵路铭%ld",i];
        model.content = @"蜀绣又名“川绣”,是在丝绸或其他织物上采用蚕丝线绣出花纹图案的中国传统工艺,18107891687主要指以四川成都为中心的川西平原一带的刺绣。😁蜀绣最早见于西汉的记载,当时的工艺已相当成熟,同时传承了图案配色鲜艳、常用红绿颜色的特点。😁蜀绣又名“川绣”,是在丝绸或其他织物上采用蚕丝线绣出花纹图案的中国传统工艺,https://www.baidu.com,主要指以四川成都为中心的川西平原一带的刺绣。蜀绣最早见于西汉的记载,当时的工艺已相当成熟,同时传承了图案配色鲜艳、常用红绿颜色的特点。";
        model.headImage = [UIImage imageNamed:@"1"];
        [self.dataArr addObject:model];
    }
    
}

- (void)createView
{
    
    cellNum = 0;
    //[self createRightNavBtn];
    
    
    [self RunLoopOptimization];
    
}



-(void)RunLoopOptimization
{
    //1、先获取当前的Runloop
    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    //定义观察者
    CFRunLoopObserverRef observer;
    CFRunLoopObserverContext context = {
        0,
        (__bridge void *)self,
        &CFRetain,
        &CFRelease,
        NULL
    };
    //创建观察者 参数一:分配空间的方式,参数二:运行循环状态,参数三:是否一直监听,参数四:优先级 参数五:回调函数的地址,参数六:上下文
    observer = CFRunLoopObserverCreate(kCFAllocatorMalloc, kCFRunLoopBeforeWaiting, YES, 0, &Callback, &context);
    //添加观察者,添加在common模式下面
    CFRunLoopAddObserver(runloop, observer, kCFRunLoopCommonModes);

    
    
    //创建定时器 (保证runloop回调函数一直在执行)
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self
                                                             selector:@selector(notDoSomething)];
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    
    
}
- (void)notDoSomething {
    // 不做事情,就是为了让 callBack() 函数一直相应
}
//MARK: 回调函数
//定义一个回调函数  一次RunLoop来一次
static void Callback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
    MomentViewController * vcSelf = (__bridge MomentViewController *)(info);
    
    if (vcSelf.saveTaskMarr.count > 0) {
        
        //获取一次数组里面的任务并执行
        SaveFuncBlock funcBlock = vcSelf.saveTaskMarr.firstObject;
        funcBlock();
        [vcSelf.saveTaskMarr removeObjectAtIndex:0];
    }

}







-(void)createRightNavBtn
{
    //导航右侧按钮
    UIButton *saveButton=[UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.frame = CGRectMake(0, 0, 40, 30);
    [saveButton setTitle:@"编辑" forState:UIControlStateNormal];
    saveButton.hidden=false;
    [saveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveIDCard:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:saveButton];
    [self.navigationItem setRightBarButtonItem:rightItem];
    
    
    
}
- (void) saveIDCard:(UIButton*)saveButton{
    for (NSInteger i = 0; i < 1000 ; i ++) {
        MomentModel *model = self.dataArr[i];
        NSString * str = [NSString stringWithFormat:@"%ld",(i+1)%10];
        model.showImage = [UIImage imageNamed:str];
        [model modeCellHeightSet];
        
    }
    
    [self.tableView reloadData];
}
#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //NSLog(@"%ld",self.dataArr.count);
    
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.dataArr count];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    
    MomentTableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    
    [cell createMomentTableViewCell:self.dataArr[indexPath.row]];
    
    MomentModel *model = self.dataArr[indexPath.row];
    if (!model.cellHeight) {
        //添加任务到数组
        __weak typeof(self) weakSelf = self;
        [self addTasks:^{
            //下载图片的任务
            [weakSelf addImageToCell:cell andTag:indexPath];
        }];
    }
    
    return cell;
}
//添加任务进数组保存
-(void)addTasks:(SaveFuncBlock)taskBlock{
    
    [self.saveTaskMarr addObject:taskBlock];
    //超过每次最多执行的任务数就移出当前数组
    if (self.saveTaskMarr.count > self.maxTasksNumber) {
        
        [self.saveTaskMarr removeObjectAtIndex:0];
    }
    
}


-(void)addImageToCell:(MomentTableViewCell*)cell andTag:(NSIndexPath*)indexPath{
    
    //UIImageView* cellImageView = [[UIImageView alloc]initWithFrame:CGRectMake(tag*(64, 5, ImageWidth, ImageHeight)];
    
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        
        NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201312/14/20131214173346_iVKdT.jpeg"]];
        
        
        //NSLog(@"imageData%@",imageData);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MomentModel *model = self.dataArr[indexPath.row];
            NSString * str = [NSString stringWithFormat:@"%ld",(indexPath.row+1)%10];
            model.showImage = [UIImage imageNamed:str];
            [model modeCellHeightSet];
            
            //
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
        });
    });
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MomentModel *model = self.dataArr[indexPath.row];
    
    if (model.cellHeight){
        return model.cellHeight;
    }
    return 130;
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}



@end

demo: https://github.com/1872784520/ZLMTableViewOptimize

码字不易,有用请喜欢,转载注明出处!!!

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

推荐阅读更多精彩内容