UILabel not aligning perfectly center when wrapping - iphone

See image for example: http://img25.imageshack.us/img25/6996/90754687.png
The grey background indicates the size of the UILabel frame.
For some reason, the first line of wrapped text doesn't seem to always center, even though I'm using UITextAlignmentCenter.
Here's the code I use to set up my labels:
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.font = [UIFont boldSystemFontOfSize:fontHeight];
titleLabel.backgroundColor = [UIColor grayColor];
titleLabel.numberOfLines = 2;
titleLabel.lineBreakMode = UILineBreakModeMiddleTruncation;
NSString * title = file.name;
CGSize maximumSize = CGSizeMake(thumbnailWidth+4,fontHeight * 3);
UIFont * font = [UIFont boldSystemFontOfSize:12];
CGSize stringSize = [title sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:titleLabel.lineBreakMode];
CGRect stringFrame = CGRectMake(0, thumbnailHeight + thumbnailPadding, thumbnailWidth + 4, stringSize.height);
titleLabel.text = title;
titleLabel.frame = stringFrame;
titleLabel.textAlignment = UITextAlignmentCenter;

Is that because there are no spaces in the text? In IB it appears to react just like your getting, if you have no spaces. Setting the line break mode to character wrap tends to center the second lines to the first, but that may not be entirely what you want either.

Related

UIScrollView and UITextView autosizing possible?

I have a view that is pushed onto the Screen via navigation controllers:
Inside is a UIScrollView.
Then inside the UIScrollView are a few static objects like Images and Labels.
Then comes the hard bit, There is a UITextView with its text loaded from different text files of varying length.
I need to be able to have the UITextView size dynamically to its contents, and the same for the UIScrollView. Is this possible?
float length = [yourText length];
textview.frame = CGRectMake(44, 87, 923, ceilf(length/142)*25);
Here 25 is the constant value assumed as text font width. From this you can set scrollview frame reference to the textview frame.
You can do that with the help of following code. I had done that code for Label and same way you can do that with the help of text-field.
NSString *cellText = "Text Of Your Text-Field";
UIFont *cellFont = [UIFont fontWithName:#"Your Font Name" size:FONT_SIZE];//UIFont *cellFont = [UIFont fontWithName:#"Helvetica-Bold" size:13.0];
CGSize constraintSize = CGSizeMake(#"Width Of Your Text-Field", MAXFLOAT);//CGSize constraintSize = CGSizeMake(220.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
int height = labelSize.height;
frame.origin.x = Starting Position of X;
frame.origin.y = Starting Position of Y;
frame.size.width = Width Of Your TextField;
frame.size.height = height;
UILabel *lblName = [[[UILabel alloc] initWithFrame:frame] autorelease];
lblName.numberOfLines = 0;
lblName.lineBreakMode = UILineBreakModeWordWrap;
lblName.textAlignment = UITextAlignmentLeft;
lblName.textColor = [UIColor whiteColor];
lblName.backgroundColor = [UIColor clearColor];
lblName.font = [UIFont boldSystemFontOfSize:13.0];
And same way you can do For the Scrollview. Just you have to set the Frame of that scrollview and you are done.
Yes you could do something like this:
if ([textView length] > int//any number you want) {
textView.frame = CGRectMake(//just adjust the size an position here);
scrollView.contentSize = CGSizeMake(//adjust scrollView size)
}
else if ([textView length] > int//just another number) {
// you can continue looping that for how often you want
}
For the int in the if statement you check how long the text is. Based on that you adjust the size of both the scrollView and textView.

UILabel getting displayed differently on 3rd and 4th gen iPods

I have a UILabel which behaves differently on 3rd & 4th Gen iPods.
My UILabel is:
<UILabel: 0x881e80; frame = (10 76; 70 28); text = 'Produits Indisponibles'; clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x863fe0>>
Now, on 4th gen iPod it works fine and text wraps into 2 lines properly but on 3rd gen iPod text wraps but second word (Indisponibles) disappears. What could be the reason?
If I increase the frame width by 1 more pixel, it works fine. Here is my code:
self.titleLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
self.titleLabel.text = #"Produits Indisponibles";
self.titleLabel.isAccessibilityElement = NO;
self.titleLabel.backgroundColor = [UIColor clearColor];
self.titleLabel.opaque = NO;
self.titleLabel.textColor = [UIColor whiteColor];
self.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
self.titleLabel.numberOfLines = 2;
self.titleLabel.highlightedTextColor = [UIColor whiteColor];
self.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
self.titleLabel.textAlignment = UITextAlignmentCenter;
self.titleLabel.font = [UIFont boldSystemFontOfSize:11];
CGSize aLabelSize = CGSizeMake(self.frame.size.width - 20, 28);
CGSize aStringSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font constrainedToSize:aLabelSize lineBreakMode:UILineBreakModeWordWrap];
CGFloat theYOrigin = self.bounds.size.height - 34;
if (aStringSize.height < 15) {
theYOrigin = theYOrigin + 14;
}
self.titleLabel.frame = CGRectMake(10, theYOrigin, aLabelSize.width, aStringSize.height);
[self addSubview:self.titleLabel];
Retina displays use Helvetica Neue as the system font, while older models use normal Helvetica. It's probably related to the different font metrics. Hard-code a font you know is available on both to see if they display consistently.
I do not see the reason but when I increased the width of the frame by 2 more pixels it worked. Anyone know the reason for this will be enlightening.

iOS: UILabel dynamic height using sizeWithFont:constrainedToSize:lineBreakMode: not working

I am trying to give my UILabel dynamic height so that my layout of other labels looks correct in both landscape and portrait.
In portrait, my text wraps to the second line, in landscape it does not. So, when using sizeWithFont:constrainedToSize:lineBreakMode: I get the same height when rotating both ways, when I had assumed it would be a larger number when the text was 2 lines.
How can I get the height of my UILabel when it has two lines of text or more (portrait) and get the new height which is one line, when in landscape?
I guess I am not understanding how to get dynamic height working...
UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, top, screen.size.width - 20, 200.0f)];
itemTitle.text = self.newsAsset.title;
itemTitle.adjustsFontSizeToFitWidth = NO;
itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
itemTitle.font = [UIFont boldSystemFontOfSize:18.0];
itemTitle.textColor = [UIColor blackColor];
itemTitle.shadowColor = [UIColor whiteColor];
itemTitle.shadowOffset = CGSizeMake(0, 1);
itemTitle.backgroundColor = [UIColor blueColor];
itemTitle.lineBreakMode = UILineBreakModeWordWrap;
itemTitle.numberOfLines = 0;
[itemTitle sizeToFit];
// Set the height
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize titleSize = [itemTitle.text sizeWithFont:itemTitle.font constrainedToSize:maximumLabelSize lineBreakMode:itemTitle.lineBreakMode];
NSLog(#"Height: %.f Width: %.f", titleSize.height, titleSize.width);
//Adjust the label the the new height
CGRect newFrame = itemTitle.frame;
newFrame.size.height = titleSize.height;
itemTitle.frame = newFrame;
// Add them!
[headerView addSubview:itemTitle];
[itemTitle release];
top += titleSize.height;
change the line where you set maximumLabelSize to
CGSize maximumLabelSize = CGSizeMake(headerView.bounds.size.width, CGFLOAT_MAX);
In your code as it is now, in either orientation you will get the same width and height, since you always pass a width of 300 to the sizeWithFont method. If you make it dynamic, maybe the result of the sizeWithFont will also change dynamically.

How can I make text in a UILabel shrink font size

If a UILabel contains too much text, how can I setup my label so that it shrinks font-sizes?
Here is how I am setting up my UILabel:
descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 30, 130, 150)];
[descriptionLabel setFont:[Utils getSystemFontWithSize:14]];
[descriptionLabel setBackgroundColor:[UIColor clearColor]];
[descriptionLabel setTextColor:[UIColor whiteColor]];
descriptionLabel.numberOfLines = 1;
[self addSubview:descriptionLabel];
descriptionLabel.adjustsFontSizeToFitWidth = YES;
descriptionLabel.minimumFontSize = 10.0; //adjust to preference obviously
The following example is tested and verified on iPhone Simulator 3.1.2:
UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 200, 30)];
descriptionLabel.font = [UIFont systemFontOfSize:14.0];
descriptionLabel.minimumFontSize = 10.0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;
descriptionLabel.numberOfLines = 1;
descriptionLabel.text = #"supercalifragilisticexpialidocious even thought he sound of it is something quite attrocious";
To resize the text in a multi-line UILabel, you can use this helper method (based on code from 11 Pixel Studios):
+ (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize {
// use font from provided label so we don't lose color, style, etc
UIFont *font = aLabel.font;
// start with maxSize and keep reducing until it doesn't clip
for(int i = maxSize; i >= minSize; i--) {
font = [font fontWithSize:i];
CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);
// This step checks how tall the label would be with the desired font.
CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
if(labelSize.height <= aLabel.frame.size.height)
break;
}
// Set the UILabel's font to the newly adjusted font.
aLabel.font = font;
}
Set the adjustsFontSizeToFitWidth property to YES.
If you want the number of lines to also increase if needed, use Steve N's solution, with the if statement as so:
if(labelSize.height <= aLabel.frame.size.height)
{
aLabel.numberOfLines = labelSize.height / font.lineHeight;
break;
}

iPhone UILabel sizeWithFont:

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 property? So my layout algorithm positions everything lower than they actually need to be.
_price = [[UILabel alloc] init];
_price.text = myPriceValue;
_price.lineBreakMode = UILineBreakModeWordWrap;
_price.numberOfLines = 3;
_price.backgroundColor = [UIColor clearColor];
_price.textColor = TTSTYLEVAR(colorPrice);
/// the follow code ignores numberOfLines and just tells me the size of the whole block.
// I'd like it to be aware of numberOfLines
//
CGSize priceSize = [_price.text sizeWithFont:_price.font
constrainedToSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
Does anyone know how to do this using the iPhone SDK?
Instead of CGFLOAT_MAX for the max height of your text calculation, try getting the size of one line with this:
[_price.text sizeWithFont:_price.font].height
and then multiplying that by the maximum # of lines you want, then plugging that into the height of the size you are constraining yourself to. It'd probably look like this:
_price = [[UILabel alloc] init];
_price.text = myPriceValue;
_price.lineBreakMode = UILineBreakModeWordWrap;
_price.numberOfLines = 3;
_price.backgroundColor = [UIColor clearColor];
_price.textColor = TTSTYLEVAR(colorPrice);
CGFloat lineHeight = [_price.text sizeWithFont:_price.font].height;
CGSize priceSize = [_price.text sizeWithFont:_price.font
constrainedToSize:CGSizeMake(maxWidth, lineHeight * _price.numberOfLines)
lineBreakMode:UILineBreakModeWordWrap];
Don't use this if you ever set number of lines to 0 as your max height will be 0 in that case; you should use CGFLOAT_MAX then.
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
Instead of trying to do it in one call, do something like this (pardon the pseudocode, it's late):
NSString *s = _price.text;
UIFont *font = _price.font;
CGFloat fontSize = font.pointSize;
while (TRUE)
{
CGSize priceSize = [s sizeWithFont: font constrainedToSize:
CGSizeMake(maxWidth, fontSize) lineBreakMode: UILineBreakModeWordWrap];
if ( /* priceSize is satisfactory */ )
{
break; // Make sure this exits, eventually!!!
}
fontSize -= 1.0; // or a smaller decrement if you like
font = // new, smaller font
}
The correct answer is, of course, you need to set numberOfLines to 0, which will cause the framework to compute the result with however many lines it needs. See also this question.
Of course it doesn't take it into account, since nothing being called or passed in has that information. You're strictly working with strings, sizes, and fonts. It's the label that has the number of lines in it.
I'm not sure what exactly your problem is; are you getting a size that's too tall or too short, or what? You can find out the number of lines of text by dividing the height of the result by the height of the font, which is the value of the ascender plus the descender, I believe.