Problems with sizes and lines in UILabel - ios

I have a little question. I developed an application that automatically fills a data set obtained from a SQLite database. These data are drawn from dynamic way, and between the data I have a frame where I insert labels dynamically. I never know the exact number of labels inside these frame because I take data from different tables of my Database. The problem I have with the labels which texts within them do not fill within the width of the label. I tried to use label.linebreakmode but still makes the break. I post the code:
There I have many objects taken from previous code, like widthFormato and widthImageFormato
if([tipoVino length]!=0){
UILabel *lblFormato = [[UILabel alloc] init];
labelX = ((widthFormato-widthImageFormatos) / 2)+10;
CGRect labelFrame = lblFormato.frame;
labelFrame.size.width = widthImageFormatos;
labelFrame.origin.x = labelX;
labelFrame.origin.y = labelY+25;
lblFormato.frame = labelFrame;
lblFormato.numberOfLines = 0;
lblFormato.lineBreakMode = NSLineBreakByWordWrapping;
[lblFormato setText:[NSString stringWithFormat:#"- %#",tipoVino]];
lblFormato.textColor = [UIColor whiteColor];
labelY = lblFormato.frame.origin.y;
[formatosImageView addSubview:lblFormato];
}

I think that you want to create labels with flexible height (not all have the same size), and must fix the width of formatosImageView.
EDITED FOR iOS7
I was using sizeWithFont that is deprecated in iOS7, I changed it for boundingRectWithSize
Try this:
UILabel *lblFormato = [[UILabel alloc] init];
lblFormato.numberOfLines = 0;
lblFormato.lineBreakMode = NSLineBreakByWordWrapping;
[lblFormato sizeToFit];
NSString *string = [NSString stringWithFormat:#"- %#", tipoVino];
[lblFormato setText: string];
//Calculate the size of the container of the lblFormato
CGSize size = [string boundingRectWithSize:CGSizeMake(widthImageFormatos, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName: [UIFont fontWithName:#"customFont" size:fontSize]} context:nil];
lblFormato.frame = CGRectMake(labelX, labelY + 25, size.width, size.height);
and you must update the labelY with:
labelY = lblFormato.frame.size.height;
Maybe it helps you.

With regards #spinillos answer, for iOS 7:
NSDictionary *attributes = #{ NSFontAttributeName : [UIFont systemFontOfSize:<#fontSize#>] };
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
initWithString: <#string#>,
attributes:attributes];
CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(<#width#>, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

Related

How to add NSString to view in define size rectangle

I need to add a sentence into my view. But the sentence is quite big. So i would like to put it inside a defined CGRect, with several lines, and change the font size, that all sentence will be visible in this CGRect. And the font size should be as big as it is possible.
Here the code that i am using:
NSAttributedString *sentence = [[NSAttributedString alloc] initWithString:#"The sentence with some words" attributes:#{NSFontAttributeName: wordsFont,NSBackgroundColorAttributeName:[UIColor yellowColor]}];
CGRect sentenceBounds;
sentenceBounds.size = [sentence size];
CGSize neededSize = CGSizeMake(MAX_WIDTH, MAX_HAIGHT);
sentenceBounds.size = neededSize;
sentenceBounds.origin = CGPointMake(0, 0);
[sentence drawInRect:sentenceBounds];
All of the functionality you're looking for is included with UILabel. Is there a reason you can't just use that?
UILabel *label = [UILabel new];
label.adjustsFontSizeToFitWidth = YES;
label.numberOfLines = 0;
label.attributedText = sentence;
label.frame = CGRectZero; //set desired frame here;
[self addSubview:label];

how to adjust UITextview height based on String dynamically in ios

I have a simple textView who's data gets populated dynamically. I want to resize the height of the textview once the data is populated so that I don't see a vertical scroll nor the text gets clipped.I want to do this task programatically. I have a label which should be placed 20 px below height of textview like "interested".I am trying to making the code.But i got some problems like Alignment issues. If i can run the program the output will display like this.
this is my Program.please help me anybody.
lblHobbies = [[UILabel alloc]initWithFrame:CGRectMake(10, 310, 300, 20)];
lblHobbies.text=#"Hobbies";
lblHobbies.font=[UIFont systemFontOfSize:16.0];
lblHobbies.textColor=[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1];
[scrollView addSubview:lblHobbies];
lblInterests = [[UILabel alloc]initWithFrame:CGRectMake(10, 420, 300, strSize.height+30)];
lblInterests.text=#"Interests";
lblInterests.font=[UIFont systemFontOfSize:16.0];
lblInterests.textColor=[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1];
[scrollView addSubview:lblInterests];
NSDictionary *attributes = #{NSFontAttributeName: [UIFont systemFontOfSize:14]};
CGRect rect =
[tViewhobbies.text boundingRectWithSize:CGSizeMake(300, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
tViewhobbies=[[UITextView alloc]init];
tViewhobbies.frame=CGRectMake(10, 330,300, rect.size.height);
[tViewhobbies setUserInteractionEnabled:NO];
tViewhobbies.backgroundColor=[UIColor colorWithRed:0.662745 green:0.662745 blue:0.662745 alpha:0.5];
tViewhobbies.delegate=self;
[scrollView addSubview:tViewhobbies];
NSDictionary *attributes1 = #{NSFontAttributeName: [UIFont systemFontOfSize:14]};
CGRect rect1 =
[tViewInterests.text boundingRectWithSize:CGSizeMake(300, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes1
context:nil];
tViewInterests=[[UITextView alloc]init];
tViewInterests.frame=CGRectMake(10, 450, 300, rect1.size.height);
[tViewInterests setUserInteractionEnabled:NO];
tViewInterests.backgroundColor=[UIColor colorWithRed:0.662745 green:0.662745 blue:0.662745 alpha:0.5];
tViewInterests.delegate=self;
[scrollView addSubview:tViewInterests];
go through below code hope helps u
self.scrollView.contentSize = CGSizeMake(320, 700);
UILabel *lblHobbies = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.bounds.origin.x + 2, self.scrollView.bounds.origin.y + 2, 75, 40)];
lblHobbies.text=#"Hobbies";
lblHobbies.font=[UIFont systemFontOfSize:16.0];
lblHobbies.textColor=[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1];
[self.scrollView addSubview:lblHobbies];
//add this after the hobbies textview so u need to calculate the height, so wy dont you put some helper method that returns the height for the text
//i took some long text that u want to display
NSString *str = #"BARCELONA, Spain -- Nokia is targeting emerging markets with three low-cost smartphones that use Google's Android operating system rather than the Windows Phone software from Microsoft, which is about to buy Nokia's phone business";
CGSize hobbiesTextViewSize = [self calculateHeightForString:str];
//now set the hobbiesTextView frame and also the text
UITextView *tViewhobbies = [[UITextView alloc]initWithFrame:CGRectMake(self.scrollView.bounds.origin.x + 2, self.scrollView.bounds.origin.y + 40, hobbiesTextViewSize.width, hobbiesTextViewSize.height+ 5)];
tViewhobbies.font = [UIFont systemFontOfSize:17.0f];
tViewhobbies.text = str;//set the text hear
[self.scrollView addSubview:tViewhobbies];
//now add the lblInterests label
UILabel *lblInterests = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.bounds.origin.x + 2, self.scrollView.bounds.origin.y + lblHobbies.frame.size.height + hobbiesTextViewSize.height + 2, 75, 40)];
lblInterests.text=#"Interests";
lblInterests.font=[UIFont systemFontOfSize:16.0];
lblInterests.textColor=[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1];
[self.scrollView addSubview:lblInterests];
NSString *str1 = #"Nokia will ditch many of the Google services that come with Android, which Google lets phone makers customize at will. Instead, the new Nokia X line announced Monday will emphasize Microsoft services such as Bing search, Skype communications and OneDrive file storage. Its home screen sports larger, resizable tiles resembling those on Windows phone.";
//now calculate the height for Interests text
CGSize interestTextViewSize = [self calculateHeightForString:str1];
UITextView *tViewInterests = [[UITextView alloc]initWithFrame:CGRectMake(self.scrollView.bounds.origin.x + 2, self.scrollView.bounds.origin.y + lblHobbies.frame.size.height + lblInterests.frame.size.height + tViewhobbies.frame.size.height + 4, interestTextViewSize.width + 2, interestTextViewSize.height+ 2)];
tViewInterests.font = [UIFont systemFontOfSize:17.0f];
tViewInterests.text = str1;
[self.scrollView addSubview:tViewInterests];
}
//our helper method
- (CGSize)calculateHeightForString:(NSString *)str
{
CGSize size = CGSizeZero;
UIFont *labelFont = [UIFont systemFontOfSize:17.0f];
NSDictionary *systemFontAttrDict = [NSDictionary dictionaryWithObject:labelFont forKey:NSFontAttributeName];
NSMutableAttributedString *message = [[NSMutableAttributedString alloc] initWithString:str attributes:systemFontAttrDict];
CGRect rect = [message boundingRectWithSize:(CGSize){320, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];//you need to specify the some width, height will be calculated
size = CGSizeMake(rect.size.width, rect.size.height + 5); //padding
return size;
}
Here is how I did it:
+(CGFloat)getLabelDymanicHeightOfStringWithText:(NSString *)text andFont:(UIFont *)font andFrame:(CGRect )frame {
CGSize maxSize = CGSizeMake(frame.size.width, 999999.0);
int height = 0;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
nil];
if (IS_IOS_6)//iOS 6 macro
{
CGSize size = [text sizeWithFont:font
constrainedToSize:maxSize
lineBreakMode:NSLineBreakByWordWrapping];
height = size.height;
}
else
{
CGRect frame = [text boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
height = frame.size.height;
}
return height+5;
}
Pass this method your text text font and frame.
You can use custom UITextView to fix the problem:
Kindly check it out: https://github.com/HansPinckaers/GrowingTextView
Textview will set height dynamically based on input string from the user.
Hope, This will help you,
:)
enter code hereYou can use label.
myLabel.text = #"Your String";
CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:CGSizeMake(320,MAX_HEIGHT_YOU_WANT_TO_SET)
lineBreakMode:NSLineBreakByWordWrapping];
CGRect frame = myLabel.frame;
frame.size.height = labelSize.height;
myLabel.frame = frame;
you can simply change the height of the textView to the height of the textView.contentSize.height. Doing this you textView will update and show all the text it contains.
textView.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width,textView.contentSize.height);
Hope this helps you.
Happy Coding :)

drawInRect:withAttributes vs drawInRect:withFont:lineBreakMode:alignment

I'm working on a new version of my app and am attempting to replace deprecated messages, but am not able to get past this one.
I can't figure out why drawInRect:withAttributes is not working. The code displays properly when drawInRect:withFont:lineBreakMode:alignment message is sent, but does not work when drawInRect:withAttributes is sent.
I'm using the same rect and font and I what I believe is the same text style. The constants are just positioning the rect just below an image, but I'm using the same rect for both calls, so I'm certain the rectangle is correct.
(note that bs.name used below is an NSString object)
CGRect textRect = CGRectMake(fCol*kRVCiPadAlbumColumnWidth,
kRVCiPadAlbumColumnWidth-kRVCiPadTextLabelYOffset,
kRVCiPadAlbumColumnWidth,
kRVCiPadTextLabelHeight);
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentCenter;
UIFont *textFont = [UIFont systemFontOfSize:16];
This doesn't work (nothing is drawn on the screen) using the variables from above
[bs.name drawInRect:textRect
withAttributes:#{NSFontAttributeName:textFont,
NSParagraphStyleAttributeName:textStyle}];
This Does work (the string is drawn properly on the screen) using the same variables from above
[bs.name drawInRect:textRect
withFont:textFont
lineBreakMode:NSLineBreakByWordWrapping
alignment:NSTextAlignmentCenter];
Any assistance would be great. Thanks.
To set the color of text you need to pass the NSForegroundColorAttributeName in the attribute as the additional parameter.
NSDictionary *dictionary = #{ NSFontAttributeName: self.font,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: self.textColor};
I've made a UIView with drawRect: containing only the code you provided
- (void)drawRect:(CGRect)frame
{
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentCenter;
UIFont *textFont = [UIFont systemFontOfSize:16];
NSString *text = #"Lorem ipsum";
// iOS 7 way
[text drawInRect:frame withAttributes:#{NSFontAttributeName:textFont, NSParagraphStyleAttributeName:textStyle}];
// pre iOS 7 way
CGFloat margin = 16;
CGRect bottomFrame = CGRectMake(0, margin, frame.size.width, frame.size.height - margin);
[text drawInRect:bottomFrame withFont:textFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
}
I don't see any difference between the outputs of these two methods. Maybe the problem is somewhere else in your code?

How to make NSStringDrawingContext shrink text?

I'm trying to use the attributed string API of iOS 6 to calculate the size of text and shrink the font size if necessary. However, I can't get it to work as the documentation says.
NSString *string = #"This is a long text that doesn't shrink as it should";
NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = 0.5;
UIFont *font = [UIFont fontWithName:#"SourceSansPro-Bold" size:32.f];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.lineBreakMode = NSLineBreakByClipping;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle };
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.title attributes:attributes];
CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(512.f, 512.f) options:NSStringDrawingUsesLineFragmentOrigin context:context];
NSLog(#"rect: %#, context: %#", NSStringFromCGRect(rect), context.debugDescription);
But the text doesn't shrink and is truncated. actualScaleFactor is always 1. The log results are:
rect:{{0, 0}, {431.64801, 80.447998}}, context:<NSStringDrawingContext: 0x14e85770> minimumScaleFactor:0.500000 minimumTrackingAdjustment:0.000000 actualScaleFactor:1.000000 actualTrackingAdjustment:0.000000 totalBounds:{{0, 0}, {431.64801, 80.447998}}
The result is the same if I use the actual drawing method and not the measuring method. If I remove the paragraph style, it makes the text wrap and doesn't shrink it. If I remove the paragraph style AND I choose a size that only allows one line of text, the text is truncated too instead of being shrunk. What is wrong? There is very little documentation or online resources dealing with NSStringDrawingContext. And I'm trying to avoid the use of sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: which is deprecated in iOS 7.
NSStringDrawingContext's minimumScaleFactor appears to be broken in iOS 7.
As far as I can make out, even in iOS 6, it didn't work for drawing; it worked for measuring, so you could work out what would happen in a context where it does work for drawing, like a UILabel. That way, you know the correct minimum height for the label.
Or, you could use the resulting scale factor to shrink the text yourself, in the knowledge that now it will fit.
Example:
- (void)drawRect:(CGRect)rect
{
// rect is 0,0,210,31
NSMutableAttributedString* s =
[[NSMutableAttributedString alloc] initWithString: #"This is the army Mister Jones."];
[s addAttributes:#{NSFontAttributeName:[UIFont fontWithName:#"GillSans" size:20]}
range:NSMakeRange(0,s.length)];
NSMutableParagraphStyle* para = [[NSMutableParagraphStyle alloc] init];
para.lineBreakMode = NSLineBreakByTruncatingTail;
[s addAttributes:#{NSParagraphStyleAttributeName:para}
range:NSMakeRange(0,s.length)];
NSStringDrawingContext* con = [[NSStringDrawingContext alloc] init];
con.minimumScaleFactor = 0.5;
CGRect result =
[s boundingRectWithSize:rect.size
options:NSStringDrawingUsesLineFragmentOrigin context:con];
CGFloat scale = con.actualScaleFactor;
// ...(could have a check here to see if result fits in target rect)...
// fix font to use scale factor, and draw
[s addAttributes:#{NSFontAttributeName:[UIFont fontWithName:#"GillSans" size:20*scale]}
range:NSMakeRange(0,s.length)];
[s drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin context:nil];
}
In iOS 6, scale is about 0.85 and you can use it as shown to shrink the text. But in iOS 7, scale remains at 1, suggesting that no shrinkage is happening and this feature of NSStringDrawingContext is now useless. I can't tell whether that's a bug or whether the feature has been deliberately abandoned.
After googling for a long time I did not find a solution working under iOS7. Right now I use the following workaround, knowing that it is very ugly. I render a UILabel in memory, take a screenshot and draw that. UILabel is able to shrink the text correctly.
But perhaps someone finds it useful.
UILabel *myLabel = [[UILabel alloc] initWithFrame:myLabelFrame];
myLabel.font = [UIFont fontWithName:#"HelveticaNeue-BoldItalic" size:16];
myLabel.text = #"Some text that is too long";
myLabel.minimumScaleFactor = 0.5;
myLabel.adjustsFontSizeToFitWidth = YES;
myLabel.backgroundColor = [UIColor clearColor];
UIGraphicsBeginImageContextWithOptions(myLabelFrame.size, NO, 0.0f);
[[myLabel layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[screenshot drawInRect:myLabel.frame];
Just wanted to post this solution as I have been battling with this for a couple hours. I could never get the text area to scale down and would always have the last lines of text cut off.
The solution for me was to not add a context and just set it to nil. I got this when looking at the example on this site. https://littlebitesofcocoa.com/144-drawing-multiline-strings
Note after getting the size the box would draw at using
pageStringSize = [myString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];
I still needed to loop through scaling down the font manually:
while (pageStringSize.size.height > 140 && scale > 0.5) {
scale = scale - 0.1;
font = [UIFont fontWithName:#"Chalkboard SE" size:24.0 *scale];
attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,[NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];
pageStringSize = [myString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];
}

How to calculate UILabel width based on text length?

I want to display an image next to a UILabel, however UILabel has variable text length, so I don't know where to place the image. How can I accomplish this?
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?
this question might have your answer, it worked for me.
For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything.
// yourLabel is your UILabel.
float widthIs =
[self.yourLabel.text
boundingRectWithSize:self.yourLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:self.yourLabel.font }
context:nil]
.size.width;
NSLog(#"the width of yourLabel is %f", widthIs);
yourLabel.intrinsicContentSize.width for Objective-C / Swift
In swift
yourLabel.intrinsicContentSize().width
The selected answer is correct for iOS 6 and below.
In iOS 7, sizeWithFont:constrainedToSize:lineBreakMode: has been deprecated. It is now recommended you use boundingRectWithSize:options:attributes:context:.
CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
options:<NSStringDrawingOptions>
attributes:#{
NSFontAttributeName: yourString.font
AnyOtherAttributes: valuesForAttributes
}
context:(NSStringDrawingContext *)];
Note that the return value is a CGRect not a CGSize. Hopefully that'll be of some assistance to people using it in iOS 7.
Swift 4 Answer who are using Constraint
label.text = "Hello World"
var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
Swift 5 Answer who are using Constraint
label.text = "Hello World"
var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
In iOS8 sizeWithFont has been deprecated, please refer to
CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:#{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];
You can add all the attributes you want in sizeWithAttributes.
Other attributes you can set:
- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName
and so on. But probably you won't need the others
CGRect rect = label.frame;
rect.size = [label.text sizeWithAttributes:#{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
label.frame = rect;
Here's something I came up with after applying a few principles other SO posts, including Aaron's link:
AnnotationPin *myAnnotation = (AnnotationPin *)annotation;
self = [super initWithAnnotation:myAnnotation reuseIdentifier:reuseIdentifier];
self.backgroundColor = [UIColor greenColor];
self.frame = CGRectMake(0,0,30,30);
imageView = [[UIImageView alloc] initWithImage:myAnnotation.THEIMAGE];
imageView.frame = CGRectMake(3,3,20,20);
imageView.layer.masksToBounds = NO;
[self addSubview:imageView];
[imageView release];
CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];
CGRect newFrame = self.frame;
newFrame.size.height = titleSize.height + 12;
newFrame.size.width = titleSize.width + 32;
self.frame = newFrame;
self.layer.borderColor = [UIColor colorWithRed:0 green:.3 blue:0 alpha:1.0f].CGColor;
self.layer.borderWidth = 3.0;
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(26,5,newFrame.size.width-32,newFrame.size.height-12)];
infoLabel.text = myAnnotation.title;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.textColor = [UIColor blackColor];
infoLabel.textAlignment = UITextAlignmentCenter;
infoLabel.font = [UIFont systemFontOfSize:12];
[self addSubview:infoLabel];
[infoLabel release];
In this example, I'm adding a custom pin to a MKAnnotation class that resizes a UILabel according to the text size. It also adds an image on the left side of the view, so you see some of the code managing the proper spacing to handle the image and padding.
The key is to use CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]]; and then redefine the view's dimensions. You can apply this logic to any view.
Although Aaron's answer works for some, it didn't work for me. This is a far more detailed explanation that you should try immediately before going anywhere else if you want a more dynamic view with an image and resizable UILabel. I already did all the work for you!!

Resources