IOS7之后有很多方法被弃用,也有很多方法添加上了。问题一大堆,我的学习方法让我越往后学,花的时间越来越多。一个方法,我不单单想知道它怎么实现,而且一定要知道为什么样实现,还能怎么样实现。
今天学习的时候,遇到一个问题,由于看教学视频,版本比较老,而我又是一个新手,没办法。一点点学吧。
问题就是设置UITableViewCell中cell内容的自适应高度。
在ios7之前有这么个方法:
<span style="font-size:18px;color:#666600;"><strong> [text sizeWithFont: constrainedToSize:];</strong></span>
但是现在被废除掉了,改用:
<span style="font-size:18px;color:#666600;"><strong>[text boundingRectWithSize:options: attributes:context:];
</strong></span>
可能这样说不明白怎么用,直接上代码:
创建表视图:
<span style="font-size:18px;color:#666600;"><strong>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSString *text = _content[indexPath.row];
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = text;
cell.textLabel.font = [UIFont systemFontOfSize:10];
cell.backgroundColor= [UIColor clearColor];
return cell;
}
</strong></span>
设置自适应:
<span style="font-size:18px;color:#666600;"><strong>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
NSString * text = [_content objectAtIndex:indexPath.row];
// NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15.0]};
CGSize textSize = [text boundingRectWithSize:tableView.bounds.size options:NSStringDrawingUsesFontLeading attributes:nil context:nil].size;
return textSize.height;
}
</strong></span>
其中有一个值得注意的地方:
<span style="font-size:18px;color:#666600;"><strong>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];</strong></span>
如果这里用这个方法的话,会程序会不断的调用这个地方的方法,程序执行顺序是,先绘制高度,然后再创建cell的实例,此时,cell并没有绘制出来,是一个nil.