二、如何重用UITableviewCell
重用的目的是为了减少内存消耗,假如有1千个cell,如果不重用,那么每一次滑动都得重新
alloc 很多很多的cell,耗费内存,同时屏幕会出现不连续的现象,晃眼睛。
重用cell很简单,在创建cell的时候,使用
alloc initwithtableviewCellStyle:reuseIdentifer这个接口创建cell实例,而非使用alloc initwithFrame
使用前者表示该cell可重用,identifer使用一个固定的NSString即可
代码如下:
复制代码-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];//首先从可重用队列里面弹出一个cell
if (cell == nil) {//说明可重用队列里面并cell,此时需要重新创建cell实例,采用下面方法
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}else{//此时表示有可重用cell,直接返回即可
NSLog(@"cell 重用啦");
}
return cell;
}
三、如何如何动态调整cell的高度?
这个问题还是比较头疼的,下面这个函数肯定要用到
复制代码
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
经过实践之后发现,可以在创建cell或者重用cell的时候,设置其frame
比如cell.frame=CGRectMake(0,0,320,450);
这个代码会有效,同时在下面这个函数里面
使用:
复制代码-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"当前是第%ld行",(long)indexPath.row);










