UILabel - Display ... when text length crosses certain length - iphone

I have placed UILabel in my application, in that I want to display the text with .... once the length of the text exceeds the certain count.
Because if the text goes longer, it gives the design issue.
Please let know which function to use.

Try this
yourLabel.lineBreakMode=UILineBreakModeTailTruncation;
If you are adding your UILabel from interface builder you can do it directly. Select you UILabel and in the Utilities column in Attriubtes Inspector=> Label section=> Line Breaks set Truncate Tail

Try this will helpful for you.
NSString *string=YourString;
int size=[YourString length];
if (size>21)
{
NSMutableString *string1 = [[NSMutableString alloc]init];
char c;
for(int index = 0;index <20 ;index++)
{
c =[string characterAtIndex:index];
[string1 appendFormat:#"%c",c];
}
[string1 appendFormat:#"..."];
string=string1;
}
Add "string" on your UILable.

#define EXCEEDED_LENGTH 8
- (NSString *) checkStringLength:(NSString *)str
{
if(str.length >= EXCEEDED_LENGTH)
{
return [NSString stringWithFormat:#"%#...",[str subStringToIndex:EXCEEDED_LENGTH-1]];
}
return str;
}
yourLabel.text = [self checkStringLength:#"Hello World !!"];
Output like Hello Wo... For better output you can trim whitespaces before pass string to function.

From the information you shared I think the autoshrink and linebreakermode may be the root cause.IT is the property which tries to show the contents in the specified frame which will decrease and adjust the font size
2 ways to sove the issue
adjust the property according to requirement
Increase the framesize of label(programmatically by finding size)
also look on the edge insets

Either you can make UILable size(length/width) Dynamic,
Or
You can UITextView with edit disable so if there will be long text it will be scrollable.

CGSize constraint = CGSizeMake(690.0, 2000.0);
CGSize size_txt_overview1 = [[headItemArray objectAtIndex:k] sizeWithFont:[UIFont fontWithName:#"Helvetica" size:18] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
UILabel *lbl_headitem = [[UILabel alloc]initWithFrame:CGRectMake(3,h, 690, size_txt_overview1.height)];
lbl_headitem.numberOfLines=0;
Please set your UILabel width and height in CGSize constraint. Best way.. and it worked for me.

This is a method for a Category of UILabel
-(void)setTruncatedTextWithDotsIfNeeded:(NSString *)text
{
float fullTextWidth = [text sizeWithFont:self.font].width;
float labelWidth = self.frame.size.width;
if(fullTextWidth<=labelWidth){
[self setText:text];
return;
}
NSString *dots = #"…";
float dotsWidth = [dots sizeWithFont:self.font].width;
NSRange fullRange = [text rangeOfString:text];
for(int i = fullRange.length; i >= fullRange.location; i--){
NSRange currentRange;
currentRange.location = 0;
currentRange.length = i;
NSString *partialText = [text substringWithRange:currentRange];
float partialTextWidth = [partialText sizeWithFont:self.font].width;
if(partialTextWidth + dotsWidth <= labelWidth){
[self setText:[NSString stringWithFormat:#"%#...",partialText]];
return;
}
}
}

Related

How to limit UILabel text length - IOS

Is it possible to limit the text length for UILabel.. I know I can limit the string whatever I am assigning to label, However I just need to know... Is there any possibility to do it in UILabel level?
In my case I just want to show only 10 characters in UILabel..
I fixed this by adding a notification in viewDidLoad: that listens to when the length exceeds a value:
- (void)limitLabelLength {
if ([self.categoryField.text length] > 15) {
// User cannot type more than 15 characters
self.categoryField.text = [self.categoryField.text substringToIndex:15];
}
}
Yes you can use :
your_text = [your_text substringToIndex:10];
your_label.text = your_text;
Hope it helps you.
NSString *string=#"Your Text to be shown";
CGSize textSize=[string sizeWithFont:[UIFont fontWithName:#"Your Font Name"
size:#"Your Font Size (in float)"]
constrainedToSize:CGSizeMake(100,50)
lineBreakMode:NSLineBreakByTruncatingTail];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 50,textSize.width, textSize.height)];
[myLabel setLineBreakMode:NSLineBreakByTruncatingTail];
[myLabel setText:string];
Further by changing the value of constrainedToSize: you can fix the maximum size of UILabel
NSString *temp = your string;
if ([temp length] > 10) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 10}];
temp = [temp substringWithRange:range];
}
coverView.label2.text = temp;
I can't see any direct way to achieve this. But we can do something, lets make a category for UILabel
#interface UILabel(AdjustSize)
- (void) setText:(NSString *)text withLimit : (int) limit;
#end
#implementation UILabel(AdjustSize)
- (void) setText:(NSString *)text withLimit : (int) limit{
text = [text substringToIndex:limit];
[self setText:text];
}
#end
You can make it in your class where you want to do that (or make it in separate extension class and import that where you want this functionality);
Now use is in following way:
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectZero];
[lbl setText:#"Hello Newbee how are you?" withLimit:10];
NSLog(#"lbl.text = %#", lbl.text);
And here is the log:
2013-05-09 15:43:11.077 FreakyLabel[5925:11303] lbl.text = Hello Newb

How do I truncate a string within a string in a UILabel?

Say I have The Dark Knight Rises at 7:45pm and I need to fit that into a fixed-width UILabel (for iPhone). How would I make that truncate as "The Dark Knight Ris... at 7:45pm" rather than "The Dark Knight Rises at 7:4..."?
UILabel has this property:
#property(nonatomic) NSLineBreakMode lineBreakMode;
You enable that behaviour by setting it to NSLineBreakByTruncatingMiddle.
EDIT
I din't understand that you wanted to truncate only a part of the string.Then read this:
If you want to apply the line break mode to only a portion of the text, create a new attributed string with the desired style information and associate it with the label. If you are not using styled text, this property applies to the entire text string in the text property.
Example
So there is even a class for setting the paragraph style: NSParagraphStyle and it has also it's mutable version.
So let's say that you have a range where you want to apply that attribute:
NSRange range=NSMakeRange(i,j);
You have to create a NSMutableParagraphStyle object and set it's lineBreakMode to NSLineBreakByTruncatingMiddle.Notice that you may set also a lot of other parameters.So let's do that:
NSMutableParagraphStyle* style= [NSMutableParagraphStyle new];
style.lineBreakMode= NSLineBreakByTruncatingMiddle;
Then add that attribute for the attributedText of the label in that range.The attributedText property is a NSAttributedString, and not a NSMutableAttributedString, so you'll have to create a NSMutableAttributedString and assign it to that property:
NSMutableAttributedString* str=[[NSMutableAttributedString alloc]initWithString: self.label.text];
[str addAttribute: NSParagraphStyleAttributeName value: style range: range];
self.label.attributedText= str;
Notice that there are a lot of other properties for a NSAttributedString, check here.
You have to set the lineBreakMode. You can either do that from Interface Builder or programmatically as follows
label.lineBreakMode = NSLineBreakByTruncatingMiddle;
please note that since iOS 5 the type of such property changed from UILineBreakMode to NSLineBreakMode.
My first idea would be two labels side-by-side both with fixed width, but I'll assume you've ruled that out for some unstated reason. Alternatively, compute the truncation manually, like this ...
- (NSString *)truncatedStringFrom:(NSString *)string toFit:(UILabel *)label
atPixel:(CGFloat)pixel atPhrase:(NSString *)substring {
// truncate the part of string before substring until it fits pixel
// width in label
NSArray *components = [string componentsSeparatedByString:substring];
NSString *firstComponent = [components objectAtIndex:0];
CGSize size = [firstComponent sizeWithFont:label.font];
NSString *truncatedFirstComponent = firstComponent;
while (size.width > pixel) {
firstComponent = [firstComponent substringToIndex:[firstComponent length] - 1];
truncatedFirstComponent = [firstComponent stringByAppendingString:#"..."];
size = [truncatedFirstComponent sizeWithFont:label.font];
}
NSArray *newComponents = [NSArray arrayWithObjects:truncatedFirstComponent, [components lastObject], nil];
return [newComponents componentsJoinedByString:substring];
}
Call it like this:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 21)];
NSString *string = #"The Dark Knight Rises at 7:45pm";
NSString *substring = #"at";
CGFloat pix = 120.0;
NSString *result = [self truncatedStringFrom:string toFit:label atPixel:120.0 atPhrase:#"at"];
label.text = result;
This generates: #"The Dark Kni...at 7:45pm"

Label Text is not wrapped

I assign a label in a table view but the text in the label does not wrap to the next line when it is too long.
My code is follow:
UILabel *food_lbl=[[UILabel alloc]init];
foodspe = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"food"]];
foodspe = [foodspe stringByReplacingOccurrencesOfString:#"(" withString:#""];
foodspe = [foodspe stringByReplacingOccurrencesOfString:#")" withString:#""];
foodspe = [foodspe stringByReplacingOccurrencesOfString:#"\n" withString:#""];
foodspe = [foodspe stringByReplacingOccurrencesOfString:#" " withString:#""];
food_lbl.text = foodspe;
food_lbl.numberOfLines=2;
food_lbl.lineBreakMode=UILineBreakModeWordWrap;
[food_lbl setFrame:CGRectMake(100, 0, 150, 100)];
[food_lbl setFont:[UIFont boldSystemFontOfSize:25.0f]];
[cell.contentView addSubview:header];
e.g. food_lbl is paneer,panjabi,pasta,pizza,Puff,chocolates
Have you tried this ?
food_lbl.numberOfLines=0;
Go to the UILabel property in the xib and make Autoshrink YES.
I'll suggest two options,
Use this method to find the required height for your text label and
set it to that:
CGFloat height = [foodspe sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(food_lbl.frame.size.width, 500) lineBreakMode:UILineBreakModeWordWrap].height;
Add a space between each word of your input text. That is change this paneer,panjabi,pasta,pizza,Puff,chocolates to paneer, panjabi, pasta, pizza, Puff, chocolates
if your listed code (shown below) was used exactly in your project, then you are adding a wrong label.
UILabel *food_lbl=[[UILabel alloc]init];
...
[cell.contentView addSubview:header];
You are adding header rather than the newly created food_lbl.

Resizing UIView based on content

I have a view with a lot of labels being populated with parsed XML. That view is within a UIScrollView. Some of the XML is too long for the labels. I'm resizing the labels based on the XML content. When the labels are re sized, they overlap the subsequent labels because my UIView (that is within the UIScrollView) isn't being re sized. I've been scouring the internet for hours trying to find an answer to this, but everything that I've tried hasn't achieved what I'm looking for. Any help would be greatly appreciated.
This is my populateLabels method.
-(void) populateLabels {
NSString *noInfo = (#"No Information Available");
lblCgName.text = _Campground.campground;
NSString *cgLoc = _Campground.street1;
NSString *cgCity = _Campground.city;
NSString *cgState = _Campground.state1;
NSString *cgCountry = _Campground.country;
NSString *cgZipPostal = _Campground.zipPostal;
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgCity];
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgState];
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgCountry];
cgLoc = [[cgLoc stringByAppendingString:#" "] stringByAppendingString:cgZipPostal];
lblCgLoc.text = cgLoc;
double dRate = [_Campground.regRate1 doubleValue];
double dRate2 = [_Campground.regRate2 doubleValue];
NSString *rate = [[NSString alloc] initWithFormat:#"$%0.2f",dRate];
NSString *rate2 = [[NSString alloc] initWithFormat:#"$%0.2f",dRate2];
if ([rate2 isEqualToString:#"$0.00"]) {
lblRate.text = rate;
} else {
rate = [[rate stringByAppendingString:#" - "] stringByAppendingString:rate2];
lblRate.text = rate;
}
double dPaRate = [_Campground.paRate1 doubleValue];
double dPaRate2 = [_Campground.paRate2 doubleValue];
NSString *paRate = [[NSString alloc] initWithFormat:#"$%0.2f",dPaRate];
NSString *paRate2 = [[NSString alloc] initWithFormat:#"$%0.2f",dPaRate2];
if ([paRate2 isEqualToString:#"$0.00"]) {
lblPaRate.text = paRate;
} else {
paRate = [[paRate stringByAppendingString:#" - "] stringByAppendingString:paRate2];
lblPaRate.text = paRate;
}
lblLocal1.text = _Campground.localPhone1;
lblLocal2.text = _Campground.localPhone2;
lblTollFree.text = _Campground.tollFree;
lblFax.text = _Campground.fax;
lblEmail.text = _Campground.email;
lblWebsite.text = _Campground.website;
NSString *gps = _Campground.latitude;
NSString *longitude = _Campground.longitude;
gps = [[gps stringByAppendingString:#", "] stringByAppendingString:longitude];
lblGps.text = gps;
lblHighlights.text = _Campground.highlights;
lblHighlights.lineBreakMode = UILineBreakModeWordWrap;
lblHighlights.numberOfLines = 0;
//label resizing
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [_Campground.highlights sizeWithFont:lblHighlights.font
constrainedToSize:maximumLabelSize
lineBreakMode:lblHighlights.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = lblHighlights.frame;
newFrame.size.height = expectedLabelSize.height;
lblHighlights.frame = newFrame;
lblTents.text = _Campground.tents;
lblNotes.text = _Campground.notes;
lblDirections.text = _Campground.directions;
lblRentals.text = _Campground.rentals;
}
Where is the - (void) populateLabels method located? If it's in a view controller, you should have easy access to the view that needs to be resized. Alternatively, if the labels (which look to already be created) have been added to the view that needs to be resized, then you can access their superview. You've already got size you need, just set set the superview's frame size at the end of the method.
If you're trying to find the size of each label first based on the string content, you'll want to use the NSString method: -sizeWithFont. There are several variations of this that allow you to specify constraints:
Computing Metrics for a Single Line of Text
– sizeWithFont:
– sizeWithFont:forWidth:lineBreakMode:
– sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
Computing Metrics for Multiple Lines of Text
– sizeWithFont:constrainedToSize:
– sizeWithFont:constrainedToSize:lineBreakMode:
Remember that UILables only show 1 line of text. Also keep in mind that this will return the size that the string will take up. Views like UILabels and UITextViews tend to add padding, so you may need to account for that when calculating the height. After you've calculated the height and placed each label, you should then know the size the superView will need to be and set it appropriately. Also, if you don't know which label will be last/lowest/furthest down in the view (the size of the superView should be the origin.y + the size.height of the last view) you can do something like this:
CGFloat totalHeight = 0.0f;
for (UIView *view in superView.subviews)
if (totalHeight < view.frame.origin.y + view.frame.size.height) totalHeight = view.frame.origin.y + view.frame.size.height;
This will give you the height of the superview if you don't already know it (and you can do the same thing for width if need be).
Do you really need to use a bunch of labels?
It seems you need to use UITextView or UIScrollView.
The general method to resize a UIView based on its subviews is sizeToFit
This method resizes your UIView automatically.
If you wanted to constrain the size, you'll need to use sizeThatFits: This method does not resize your UIView automatically, rather it returns the size.
Just a side note: These two methods only factor in subviews so not drawings nor Core Text.

Loop through labels iPhone SDK

Ok I have 8 labels and I want to loop through them but am having no luck.
This is what I have tried.
for (int i; i = 0; i < 10; i++)
{
double va = [varible1.text doubleValue] + i;
int j = 0 + I
label(j).text= [[NSString alloc]initWithFormat:#"%2.1f", va];
}
This errors out. My labels are named like this label0, label1, label2
Any help would be appreciated.
label(j) is NOT equivalent to label0, label1, etc.
You should create an NSArray of labels, then you can access them with [arrayOfLabels objectAtIndex:j]. If you're not sure what this means, please read the documentation about NSArray...
You should maybe add all your labels to a C array, probably in -viewDidLoad
UILabel* labels[] = { label0, label1, label2, ... };
(not entirely sure about the syntax)
and then access them like
labels[i].text = ...
By the way, I think you're leaking memory here:
labels[i].text = [[NSString alloc]initWithFormat:#"%2.1f", va];
initWithFormat: will return a string with a retain count of 1. labels[i].text will retain that value again. You should release the string after setting the label's text. I'd probably just autorelease it here:
labels[i].text = [[[NSString alloc]initWithFormat:#"%2.1f", va] autorelease];
or use stringWithFormat (which returns an autoreleased string):
labels[i].text = [NSString stringWithFormat:#"%2.1f", va];
for (UILabel *lbl in self.view.subviews)
{
[lbl setFont:[UIFont fontWithName:#"AppleGothic" size:22]];
}
it will change all the labels in your ViewController by just giving tags to labels.
If you cannot or do not want to put your labels in an array, you could iterate through the UIViews using the tag field as an index. You store the index numbers in them (either through IB or programatically) and then get each label using: (UIView *)viewWithTag:(NSInteger)tag.
See below (set theView to the view your labels reside in):
for (int i; i = 0; i < 10; i++)
{
double va = [varible1.text doubleValue] + i;
UILabel * label = [theView viewWithTag: i];
label.text= [[NSString alloc]initWithFormat:#"%2.1f", va];
}