【问题标题】:How can I know the label's numbers of line?我怎么知道标签的行数?
【发布时间】:2015-05-20 04:19:53
【问题描述】:

我的标签有问题。我正在使用滑块调整标签字体的大小,但我必须保持标签的行数。例如,当我调整它的大小时,我有 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];

【问题讨论】:

标签: ios iphone xcode ios8 label


【解决方案1】:
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;
}

【讨论】:

    【解决方案2】:

    使用这个:

    - (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);
    }
    

    希望这会有所帮助... :)

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 2017-02-21
      • 2022-09-23
      相关资源
      最近更新 更多