iPhone UILabel sizeWithFont:

后端 未结 5 1200
刺人心
刺人心 2020-12-09 06:37

I\'m trying to measure the visual size of a NSString that takes into account the number of lines I can render. However, sizeWithFont doesn\'t take into account numberOfLines

5条回答
  •  孤城傲影
    2020-12-09 07:14

    Instead of CGFLOAT_MAX for the max height of your text calculation, try getting the size of one line with this:

    [_price.text sizeWithFont:_price.font].height
    

    and then multiplying that by the maximum # of lines you want, then plugging that into the height of the size you are constraining yourself to. It'd probably look like this:

    _price = [[UILabel alloc] init];
    _price.text = myPriceValue;
    _price.lineBreakMode = UILineBreakModeWordWrap;
    _price.numberOfLines = 3;
    _price.backgroundColor = [UIColor clearColor];
    _price.textColor = TTSTYLEVAR(colorPrice);
    CGFloat lineHeight = [_price.text sizeWithFont:_price.font].height;
    CGSize priceSize = [_price.text sizeWithFont:_price.font
            constrainedToSize:CGSizeMake(maxWidth, lineHeight * _price.numberOfLines)
            lineBreakMode:UILineBreakModeWordWrap];
    

    Don't use this if you ever set number of lines to 0 as your max height will be 0 in that case; you should use CGFLOAT_MAX then.

提交回复
热议问题