tableviewcell自适应高度当中遇到添加label作为contentView,在实际显示时右侧出现空白

今天在自己写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);之后添加

cellFrame.size.width=[UIScreen mainScreen].bounds.size.width;
便可以解决在实际显示时右边部分文字宽度怎么弄都感觉少了一部分的问题

运行之后效果图如下:



http://my.oschina.net/ioslighter/blog/390880?fromerr=WmV4Nxxn

这篇博客讲述的问题跟我类似,大家也可以看看

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值