iPhone UILabel sizeWithFont:

后端 未结 5 1199
刺人心
刺人心 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:27

    Use the UILabel's sizeToFit instead of sizeWithFont: to layout a multi-line UILabel, since sizeWithFont: will truncate the string (see apple docs). The following code reduces the font size of a label until the text fit into a the specified size... multiple lines of text will be used as soon as they fit into the specified height:

    -(void)setFontSizeOfMultiLineLabel: (UILabel*)label 
            toFitSize: (CGSize) size 
            forMaxFontSize: (CGFloat) maxFontSize 
            andMinFontSize: (CGFloat) minFontSize 
            startCharacterWrapAtSize: (CGFloat)characterWrapSize{
    
    CGRect constraintSize = CGRectMake(0, 0, size.width, 0);
    label.frame = constraintSize;
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 0; // allow any number of lines
    
    for (int i = maxFontSize; i > minFontSize; i--) {
    
        if((i < characterWrapSize) && (label.lineBreakMode == UILineBreakModeWordWrap)){
            // start over again with lineBreakeMode set to character wrap 
            i = maxFontSize;
            label.lineBreakMode = UILineBreakModeCharacterWrap;
        }
    
        label.font = [label.font fontWithSize:i];
        [label sizeToFit];
        if(label.frame.size.height < size.height){
            break;
        }       
        label.frame = constraintSize;
      } 
    }
    

    Call this with a label that has your favorite text and font:

    UILabel *label = [[UILabel alloc] initWithFrame: CGRectZero];   
    label.backgroundColor = [UIColor clearColor];   
    label.textColor = [UIColor whiteColor];
    label.text = text;
    label.font = [UIFont fontWithName: @"Helvetica" size: 16];
    [self setFontSizeOfMultiLineLabel: label toFitSize: CGSizeMake(200, 44) forMaxFontSize: 16 andMinFontSize: 8 startCharacterWrapAtSize: 11]; 
    

    The startCharacterWrapAtSize parameter lets you choose to use characterWrap starting at the giving font size. This should save space in the case wordWrap would use really small fonts.

    edit: bugfix

提交回复
热议问题