Frage

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.

War es hilfreich?

Lösung

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];

Andere Tipps

You have change frame of UILabel or UITextView which of them might be using to change accordingly.

 CGFloat actualMessageFontSize = 12.0;
CGSize messageSize = [message sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0f] minFontSize
//set frame accordingly
yourLabel.frame = CGReactMake(yourLabel.frame.origin.x,yourLabel.frame.origin.y,messageSize.width,messageSize.wiheight,);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top