Posted by Lenka on December 17, 2010
If you create your UI programatically for iOS (as is good practice), you might come across a problem with the UILabel: what size should it be to fit the text perfectly? You might get away with just making the label very large, but this will not work if you need to use the text size in some calculations later in your code.
To instantiate a UILabel with a fitting frame, you can do the following:
NSString * myText = [NSString stringWithString:@"some text"]; //get size of the text: CGFloat constrainedSize = 265.0f; //or any other size UIFont * myFont = [UIFont fontWithName:@"Arial" size:19]; //or any other font that matches what you will use in the UILabel CGSize textSize = [myText sizeWithFont: myFont constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; //create a label: CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height); UILabel *label = [[UILabel alloc] initWithFrame:labelFrame]; [label setFont:myFont]; [label setText:myText]; ... [label release];