我怎么知道标签的行数?

时间:2015-05-20 04:19:54

标签: ios iphone xcode ios8 label

我的标签有问题。我正在使用滑块调整标签的字体大小,但我必须保持标签的行数。例如,当我调整大小时,我有3行文字。它必须只维持3行。但在我的代码中,当我调整字体大小时,标签的行数不能保持。谢谢你的帮助。

这是我的代码:

   float fontSize = self.sliderFont.value;

   self.lblQuotesForImg.font = [UIFont fontWithName:self.lblQuotesForImg.font.fontName size:fontSize];


   [self.lblQuotesForImg setLineBreakMode:NSLineBreakByWordWrapping];
   self.lblQuotesForImg.numberOfLines = 0;

   [self.lblQuotesForImg sizeToFit];

2 个答案:

答案 0 :(得分:0)

Use this code for find no of line for label

NSInteger oneLineHeight = [self findHeightForText:@"A" havingWidth:width andFont:font].height;
    NSInteger totalHeight = [self findHeightForText:txt havingWidth:width andFont:font].height;
    NSInteger noOfLines = totalHeight/oneLineHeight;

- (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
        //iOS 7
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{ NSFontAttributeName:font }
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height + 1);
    }
    return size;
}

答案 1 :(得分:0)

使用此:

- (int)lineCountForText:(NSString *) text
{
    UIFont *font = [UIFont fontWithName:self.lblQuotesForImg.font.fontName size:fontSize];

    CGRect rect = [text boundingRectWithSize:CGSizeMake(200, MAXFLOAT)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName : font}
                                     context:nil];

    return ceil(rect.size.height / font.lineHeight);
}

希望这有助于......:)