今天在自己写tableviewcell动态高度的时候遇到一个问题,就是在cell当中添加label作为contentview
,显示文字。可是文字右边部分会出现空白,不是充满整个tableview,如下图所示:
代码如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identify=@"myCell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identify];
if (cell==nil)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.tag = 1;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.highlightedTextColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.opaque = NO;
label.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:label];
}
UILabel *label = (UILabel *)[cell viewWithTag:1];
NSString *text;
text = [textArray objectAtIndex:indexPath.row];
CGRect cellFrame = [cell frame];
cellFrame.origin = CGPointMake(0, 0);
label.text = text;
CGRect rect = CGRectInset(cellFrame, 16, 16);
CGRect rect=cellFrame;
label.frame = rect;
[label sizeToFit];
if (label.frame.size.height > 18) {
cellFrame.size.height = 50 + label.frame.size.height - 18;
}
else {
cellFrame.size.height = 50;
}
[cell setFrame:cellFrame];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
可是当打印cell和label的frame.size.width都是320,此时project当中已经适配了iPhone6/iPhone6Plus,只是StoryBoard/Xib中的设计视图宽度是320。
这是因为你是在cell显示之前打印size的,这个时候的size还是你这个cell在StoryBoard/Xib中的设计视图中的大小。
在iPhone6尺寸屏幕上,跟StoryBoard/Xib中的设计视图宽度医院,也出现第一幅图那样的情况,小弟还不是很明白。
至于解决右边空白部分的方法,可以通过[UIScreen mainScreen]获取当前屏幕size进行计算,由于小弟的tableview宽度是屏幕宽度,
故此在上面代码cellFrame.origin = CGPointMake(0, 0);之后添加
运行之后效果图如下:
http://my.oschina.net/ioslighter/blog/390880?fromerr=WmV4Nxxn
这篇博客讲述的问题跟我类似,大家也可以看看