Search code examples
iphoneobjective-cnsstringheightcgsize

Getting CGSize for NSString?


I am trying to get a CGSize for an NSString but I am having issues. Here is the code I am using:

CGFloat actualMessageFontSize;
CGSize messageSize = 
 [message sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" 
                                       size:14.0f] 
           minFontSize:14.0f 
        actualFontSize:&actualMessageFontSize 
              forWidth:(alertViewWidth - textIndent) 
         lineBreakMode:NSLineBreakByWordWrapping];

I NSLog the CGSize after this code and the height doesn't change, even if I put a massive NSString into it. Do you know why this might happen and or what I should try instead?

Thanks.


Solution

  • use this method and

    -(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
    {
        [text retain];
        [withFont retain];
        CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
    
        [text release];
        [withFont release];
    
        return suggestedSize.height;
    }
    

    and use it like bellow... i use this for UILable see the code..

        UILabel *lblAddress = [[UILabel alloc]init];
        [lblAddress setFrame:CGRectMake(110, 31, 200, 31)];        
        lblAddress.text = @"ABDKFNKG KKGK jfnjgdf gdklfg fldgmfkgml f";
        lblAddress.lineBreakMode = UILineBreakModeWordWrap;
        lblAddress.numberOfLines = 0;///write this line for multiple line and set 0 or anything lese
        lblAddress.font = [UIFont fontWithName:@"Helvetica" size:12];
    
        lblAddress.frame = CGRectMake(lblAddress.frame.origin.x, lblAddress.frame.origin.y, 
                                 200,[self calculateHeightOfTextFromWidth:lblAddress.text :lblAddress.font :200 :UILineBreakModeWordWrap] ); 
    
        lblAddress.textColor = [UIColor darkGrayColor];
    
        [self.view addSubview:lblAddress];