UITableViewCell中的IOS UILabel Multiline

时间:2014-07-23 22:12:16

标签: ios uitableview uilabel

我正在使用自定义UITableViewCell并且我在我的单元格内部有UILabel,但问题是当我将文本设置为我的UILabel文本注定要顶部。

this is my screen shot

这是我的代码:

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *simpleTableIdentifier = @"EventsTBC";

    EventsTBC *cell = (EventsTBC *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EventsTBC" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    cell.EventText.numberOfLines = 0;
    cell.EventText.font = [self fontForCell];
    cell.EventText.textAlignment = NSTextAlignmentRight;


   // [cell.EventText setFrame:CGRectMake(-30, 30, 300, [[Tools alloc] heightForText:[[Tools alloc] warpText:[Events objectAtIndex:indexPath.row]]])];

    [cell.EventText setLineBreakMode:NSLineBreakByWordWrapping];

    cell.EventText.text = [[Tools alloc] warpText:[Events objectAtIndex:indexPath.row]];

    cell.EventText = [self sizeToMultiline:cell.EventText];

    cell.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.10];

    return cell;
}

- (UIFont *)fontForCell
{
    return [UIFont boldSystemFontOfSize:18.0];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    //    return 150;
  return [[Tools alloc] heightForText:[[Tools alloc] warpText:[Events objectAtIndex:indexPath.row]]];

}

heightForText方法给我的文字高度:

- (CGFloat)heightForText:(NSString *)bodyText
{
    UIFont *cellFont = [UIFont systemFontOfSize:17];
    CGSize constraintSize = CGSizeMake(300, MAXFLOAT);
    CGSize labelSize = [bodyText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = labelSize.height;
    NSLog(@"height=%f", height);
    return height;
}

warpText方法替换\ n使用\ n创建新行。

1 个答案:

答案 0 :(得分:0)

打印高度值时,看起来是否不正确?

最近不推荐使用sizeWithFont方法,对我而言,它已停止工作。

我用这样的东西替换了它,感谢本网站的另一个答案:

NSAttributedString *attributedText = [[NSAttributedString alloc]
                                          initWithString:bodyText
                                          attributes:@
                                          { NSFontAttributeName: cellFont}];

CGRect rect = [attributedText boundingRectWithSize:(CGSize){300, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];

CGFloat height = rect.size.height;