UILabel改变了它的内容的高度

时间:2015-06-24 12:01:10

标签: ios objective-c uilabel

我正在编写一个UILabel,它应该根据它的内容改变它的大小。这是我的代码:

- (NSDictionary *)labelAttributesForText:(NSString *)text andWidth:        (CGFloat)width
{
    CGSize constrain = CGSizeMake(width, FLT_MAX);

    UIFont *labelFont = [UIFont fontWithName:@"HelveticaNeueInterface-Regular"     size:17];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

    NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              labelFont, NSFontAttributeName,
                              paragraphStyle, NSParagraphStyleAttributeName,
                              nil];

    CGRect labelRect = [text boundingRectWithSize:constrain
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attrDict
                                          context:nil];
    CGSize labelSize = labelRect.size;

    int numberOfLines = (CGFloat)labelSize.height / labelFont.lineHeight;

    NSLog(@"%s:%f",__PRETTY_FUNCTION__,labelSize.height);
    NSLog(@"%s:%f",__PRETTY_FUNCTION__,labelFont.lineHeight);
    NSLog(@"%s:%d",__PRETTY_FUNCTION__,numberOfLines);

    NSDictionary *labelFormatings = @{@"labelHeight":[NSString stringWithFormat:@"%f",labelSize.height],
                                      @"numberOfLines":[NSString stringWithFormat:@"%d",numberOfLines]};
    return labelFormatings;
}

该方法在cellForRowAtIndexPath中调用。问题是,它计算错误的高度,这意味着当我为给定文本调用方法并将其父UILabel设置为计算的高度时,文本不会适合UILabel。此外,numberOfLines变量存在问题,该变量使用labelFont.lineHeight的错误值计算,您可以在NSLog语句中看到。所以我的问题是我能做些什么来获得正确的高度以及为什么labelFont.lineHeight等于0?

修改

这里是我的cellForRowAtIndexPath:方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault         reuseIdentifier:reuseIdentifier];
    }

    NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat.     Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla     pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui         officia deserunt mollit anim id est laborum.";

    cell.textLabel.text = text;

    //_labelHeight = [self computeHeightWithText:text font:cell.textLabel.font width:cell.frame.size.width];
    _labelHeight = [self labelHeightForText:text andWidth:cell.frame.size.width];
    NSLog(@"%slabel Height:%f",__PRETTY_FUNCTION__,_labelHeight);
    NSLog(@"%s:%@",__PRETTY_FUNCTION__,cell.textLabel.font);

    cell.textLabel.numberOfLines = _labelHeight / cell.textLabel.font.lineHeight;


    return cell;
}

突然我做了一些改动,现在这个方法名为labelHeightForText:andWidth:。

3 个答案:

答案 0 :(得分:2)

使用此代码

-(CGFloat)getLabelHeightForFont:(NSString *)fontName andString:(NSString *)str andSize:(float)fontSize andLabelWidth:(float)lblWidth
    {
        NSString *text = str;
        CGFloat width = lblWidth;
        UIFont *font = [UIFont systemFontOfSize:fontSize];
        NSAttributedString *attributedText =
        [[NSAttributedString alloc]
         initWithString:text
         attributes:@
         {
         NSFontAttributeName: font
         }];
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        CGSize size = rect.size;
        return size.height;

    }

并使用此方法调用方法并获取标签的高度,然后更新框架

 CGFloat lbl_height = [self getLabelHeightForFont:@"System- System" andString:@"your string or message" andSize:15 andLabelWidth: yourLabel.frame.size.width]
        lbl_address.numberOfLines = 0;
        lbl_address.textAlignment = NSTextAlignmentLeft;
        [lbl_address setLineBreakMode:NSLineBreakByWordWrapping];
        lbl_address.frame = CGRectMake(lbl_address.frame.origin.x, lbl_address.frame.origin.y, lbl_address.frame.size.width, lbl_height+5);

答案 1 :(得分:2)

试试这个并告诉我,如果这有帮助

NSString *yourText = [arr1 objectAtIndex:indexPath.row]; // your text

    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIFont fontWithName:@"Avenir Next" size:14], NSFontAttributeName,
                                [UIColor grayColor], NSForegroundColorAttributeName,
                                nil]; // set custom attributes

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:yourText attributes:attributes];

    CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(625, CGFLOAT_MAX)
                                 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                 context:nil]; //here 625 is width of label

    NSLog(@"height = %f", paragraphRect.size.height);

答案 2 :(得分:1)

尝试使用此代码手动计算高度:

- (CGFloat)computeHeightWithText:(NSString *)text font:(UIFont *)font width:(CGFloat)width
{
    UILabel *gettingSizeLabel = [[UILabel alloc] init];
    gettingSizeLabel.font = font;
    gettingSizeLabel.text = text;
    gettingSizeLabel.numberOfLines = 0;

    CGSize maximumLabelSize = CGSizeMake(width, MAXFLOAT);

    CGSize expectedSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];

    return expectedSize.height;
}