Label Text is not wrapped - iphone

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.

Related

How to set Line Spacing in UI Text View (Empty text view) to enter message with line space

In my app i need to set some line spacing on ui text view..
I know we can do it for non editable textviews / labels using paragraph style spacing
But in my app when i enter text it was not working,
I can do it only when i have a predefined text on it, if once i clear the text paragraph sty will not work
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.minimumLineHeight = 35.f;
paragraphStyle.maximumLineHeight = 35.f;
UIFont *font = [UIFont fontWithName:#"AmericanTypewriter" size:18.f];
NSString *string = #"This is a test";
NSDictionary *attributtes = #{
NSParagraphStyleAttributeName : paragraphStyle,
};
deedTextView.font = font;
deedTextView.attributedText = [[NSAttributedString alloc] initWithString:string
attributes:attributtes];
But, I dont have any pre defined text like NSString *string = #"This is a test";
Text view must be empty, while begin
I had the same Problem. Based on Sergius answer I came up with the following working solution.
The problem with Sergius answer was that all other already set attributes will be overwritten (Font, Color...)
So it is better to edit the existing typingAttributes:
NSDictionary* d = deedTextView.typingAttributes;
NSMutableDictionary* md = [NSMutableDictionary dictionaryWithDictionary:d];
[md setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
deedTextView.typingAttributes= md;
One simple option that comes to mind is the following.
Using one of those 2 methods from UITextViewDelegate you can achieve what you want:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- (void)textViewDidChange:(UITextView *)textView;
You algorithm is the following - take the textView.text, convert it to the style of your needs and set textView.text as textView.attributedText
You can also try setting this:
deedTextView.typingAttributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];

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"

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

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

Autofit label, CGSize gives value zero

I want to change the size of a label depending on how big it is. I set a breakpoint on the first line, and as I go down I see that "tagsSize" actually has a value when I get to the line that starts with CGSize, it is then changed to zero after that line. I actually used this same code, with changes of course, in a different class of the same project and it is working fine. I am probably looking over something. Please take a look and let me know what I am doing wrong.
_tagsArray = [[NSMutableArray alloc] initWithObjects:#"Astronaut", #"iPhone", #"iOS", #"Software Engineer", #"Carpentry", #"Landscape Design", #"Doctor", #"Actor", #"CEO", #"iOS Developer", #"Software Engineer", #"Carpentry", #"Landscape Design", #"Doctor", #"Actor", #"CEO", #"iOS Developer", nil];
_tagsString = [_tagsArray componentsJoinedByString:#", "];
_tagsLbl.font = [UIFont fontWithName:#"Helvetica" size:18];
CGSize tagsSize = [_tagsString sizeWithFont:[_tagsLbl font]];
NSLog(#"%f", tagsSize.width);
CGFloat tagsWidth = tagsSize.width;
Where do you alloc the UILabel? I think it is nil when you use it..
try this:
CGSize size = [string sizeWithFont:[UIFont boldSystemFontOfSize:fontb]
constrainedToSize:CGSizeMake(TEXTLABEL_WIDTH, 1000)
lineBreakMode:UILineBreakModeCharacterWrap];