How to find all characters in the first line of the uilabel - ios

I want to calculate number of lines and find all characters in the first line of the UILabel dynamically from given text. I'm using wordwrapping for uilabel. Is it possible. Please help and guide me.

try like this
UILabel *thisyourlabel = [[UILabel alloc] initWithFrame:CGRectZero];
thisyourlabel.numberOfLines = 0;
thisyourlabel.lineBreakMode = UILineBreakModeWordWrap;
thisyourlabel.text = #"I want to calculate number of lines and find all characters in the first line of the UILabel dynamically from given text. I'm using wordwrapping for uilabel. Is it possible. Please help and guide me";
CGRect frame = thisyourlabel.frame;
frame.size.width = 200.0f;
frame.size = [thisyourlabel sizeThatFits:frame.size];
thisyourlabel.frame = frame;
CGFloat lineHeight = thisyourlabel.font.leading;
NSUInteger linesInLabel = floor(frame.size.height/lineHeight);
NSLog(#"Number of lines in label: %i", linesInLabel);
[self.view addSubview: thisyourlabel];

Related

Adding UILabels to UIView dynamically

I have a web service that brings some text data back. The idea is to extract the text and create UILabels for the text to show on screen. I however, do not know two things:
How many labels are needed
The length of the text
Due to having no prior knowledge of these things I need a way to create some labels that have the right length for the text it contains.
I've managed to store the data into some objects that are in an array and then iterate through them creating the labels.. something like this:
for (BBItemAttributes *attribute in self.item.productAttributes){
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 50, 10)];
label.text = attribute.displayTemplate;
[self.scrollView addSubview:label];
}
Obviously the problem here is due to creating the UILabels in code and having each one a hard coded CGRect size they are all onto of each other and sometimes don't fit in their respective boxes due to text being too long.
I need a way to line the labels up all on the same X axis point and on different Y axis points, so that they sit next to each other a certain space apart.
Is there a better way to do this?
You need to do something like this;
CGFloat yOrigin = 100;
CGFloat fixedSpace = 10;
for (BBItemAttributes *attribute in self.item.productAttributes)
{
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, yOrigin, 50, 10)];
label.text = attribute.displayTemplate;
label.numberOfLines = 0;
[label sizeToFit]; // Resizes label to fit the text.
[self.scrollView addSubview:label];
yOrigin += label.frame.size.height + fixedSpace;
}
Try this. it will help you.
float yAxis = 0;
for (int i = 0; i< 50; i++)//for (BBItemAttributes *attribute in self.item.productAttributes){
{
CGSize size;
UIFont *font = [UIFont systemFontOfSize:15.0]; // Set Your Font
//Your String = attribute.displayTemplate
if (ios7)//Condition to check if ios7
{
//iOS 7
CGRect frame = [#"Your String" boundingRectWithSize:CGSizeMake(50, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:font}
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
}
else
{
//iOS 6.0
size = [#"Your String" sizeWithFont:font constrainedToSize:CGSizeMake(50, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
}
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, yAxis, 50, size.height)];
label.text = #"Your String";//attribute.displayTemplate
label.numberOfLines = 0;
label.tag = i; // Set tag if you want to access in future. :)
[self.scrollView addSubview:label];
// Increase yAxis
yAxis = yAxis + size.height + 10;//10 is extra space if you want between two label
}
// Do Not forget to set Contentsize of your ScrollView.
self.scrollView.contentSize = CGSizeMake(320, yAxis + 20);
If your showing a data structure that is a like a list of labels, I would suggest that you use UITableViewController for showing the list.It has the built in facility and properties that make it easy to display a list of objects.
Now the answer to your first Question.You can get the number of labels by determining the number of objects that are in your array. Something like this :
NSInteger *noOfLabels = yourArray.count;
As far as the length of the text is concerned, I suggest not keeping it very lengthy because Labels are not good for lengthy texts. You can however, specify the number of a lines for a particular label in case if it has lengthy text.This will make the text appear in two lines. Though you will have to adjust width and height accordingly.
You can get the text length by doing something similar to this :
NSString *text;
NSInteger *i = (NSInteger*)[text length];
Hope this helps.

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

Initializing words of a sentence stored in a string into UILabels

I am trying to initialise the words of a sentence into UIlabels in the order of the word of the sentence every time I click on a UIbutton.
I also want to recognise when the sentence in the different labels is approaching the end of the screen, which then takes the next word and puts it in the line below the words of the sentence like pressing Enter in Microsoft Word.
I have tried this code but it loads all the words on the same spot.
- (void)change:(id)sender
{
NSString *sentence = #"i am a boy with passion";
NSArray *array = [sentence componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" "]];
CGFloat xVal = 11.0;
for (NSString *words in array) {
UILabel *labelText = [[UILabel alloc]initWithFrame:CGRectMake(xVal, 50, 300, 80)];
labelText.layer.borderColor = [UIColor blueColor].CGColor;
labelText.layer.borderWidth = 6.0;
labelText.backgroundColor = [UIColor clearColor];
labelText.textColor = [UIColor blackColor];
labelText.font = [UIFont boldSystemFontOfSize:20.0f];
labelText.text = words;
xVal=+200;
[self.view addSubview:labelText];
[labelText setUserInteractionEnabled:YES];
[labelText sizeToFit];
xVal=+200; means xVal=200. So except first label all others got same origin. Thats why they got over lapped.
For finding whether the label moved out of bounds
Initialise yVal outside for loop,
Inside the loop add
CGFloat width = [words sizeWithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]].width;
if (self.view.frame.size.width<xVal+width) {
yVal+=50;
xVal = 11;
}
UILabel *labelText = [[UILabel alloc]initWithFrame:CGRectMake(xVal, yVal, 300, 80)];
Make sure to use, a)the font you would be using for label in finding the width, b) adjust increment in yVal according to yor need.
Dont forget to change xVal=+200; to xVal+=200;
Your problem is this line:
xVal=+200;
This is the same as saying xVal = 200; the plus sign means positive 200 rather than 200 more. Try this instead:
xVal += 200;

Objective-C: Text on my UILabel is not wrapping properly

I'm having a little trouble with a uilabel that should display 1 of 5 random strings. Sometimes the entire string displays with no problem, but more often than not, some of the text is cut off. Here's what I currently have:
// These are the 5 NSStrings which are placed in an array.
NSString *badOne = #"Bad? Your bill is nothing. I would consider that good service. SMDH.";
NSString *badTwo = #"You left out the amount dude.";
NSString *badThree = #"I can't tell you what the tip should be, if you don't tell me how much you dropped.";
NSString *badFour = #"Forgetting something?";
NSString *badFive = #"The tip should be over 9000... /n kidding.";
NSArray *badComments = [[NSArray alloc] initWithObjects:badOne, badTwo, badThree, badFour, badFive, nil];
// A random string is selected and assigned to badJoke.
int rand = arc4random()%5;
NSString *badJoke = [badComments objectAtIndex:rand];
// Here's the problematic code:
[_mainLabel setText:(badJoke)];
[_mainLabel setFrame:CGRectMake(50, 295, 200, 80)];
_mainLabel.adjustsFontSizeToFitWidth = NO;
_mainLabel.numberOfLines = 0;
[_amountTextField resignFirstResponder];
// This is a separate label, completely unrelated.
[_tipAmount setText:#""];
So for example, one of the times it might show "Bad? Your bill is no".
I've also tried without the setFrame line and no luck.
Any help would be appreciated. Thanks.
Ideal solution is to calculate the exact frame needed to display the text inside the lable...
NSString *badJoke = [badComments objectAtIndex:rand];
CGSize maximumSize = CGSizeMake(200, CGFLOAT_MAX);//you can give any max width which you feel that suits you...
UIFont *font = [UIFont systemFontOfSize:16];/Give your font size
CGSize size = [badJoke sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
//size.height will get you the total height of the lable to be created.
_mainLable=[[UILable alloc]initWithFrame:CGRectMake(50, 295, size.width, size.height)];
//if you haven't initialized.Or else you can use the same as you were using..[_mainLabel setFrame:CGRectMake(50, 295, size.width, size.height)];
_mainLabel.text= badJoke;
_mainLabel.lineBreakMode=NSLineBreakByWordWrapping;
_mainLabel.numberOfLines = 0;
I am not sure with the syntax,because i wrote the code on my notepad.Hope it works for you.Happy coding :)

Having difficulty wrapping text

I use the following code to add text in IOS
//Set up label frame
UILabel *tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 10, 210, 80)];
self.answer_text_label = tempLabel;
[tempLabel release];
[self.preview_answer_container addSubview:self.answer_text_label];
//Populate label with text
self.answer_text_label.text = self.answer.text;
self.answer_text_label.numberOfLines = 4;
self.answer_text_label.lineBreakMode = UILineBreakModeWordWrap;
[self.answer_text_label sizeToFit];
However, the result I get is as such, the text seems to overflow to the right instead of staying within the frame as stipulated in my label setup 'CGRectMake(100, 10, 210, 80)'
The wrapping works if I change to self.answer_text_label.numberOfLines = 0. But this will not work for me since I need to constrain the text within my stipulated label frame.
Any way I can wrap the text and keep to only 4 lines?
EDIT:
Try the suggested code
self.answer_text_label.text = self.answer.text;
[self.answer_text_label sizeToFit];
CGRect labelRect = self.answer_text_label.frame;
labelRect.origin.y = CGRectGetMaxY(labelRect);
labelRect.size = self.answer_text_label.frame.size;
self.answer_text_label.frame = labelRect;
result as follows. Did not seem to solve my problem
Try setting frame explicitly -
[self.answer_text_label sizeToFit];
CGRect labelRect = self.answer_text_label.frame;
labelRect.origin.y = CGRectGetMaxY(labelRect);
labelRect.size = self.answer_text_label.frame.size;
self.answer_text_label.frame = labelRect;
EDIT - Don't need to use this, just use following -
remove these of code just use below, no other property of frame, remove sizeToFit as well -
self.answer_text_label.numberOfLines = 4;
self.answer_text_label.lineBreakMode = UILineBreakModeWordWrap;
For vertical alignment - (With above line of code, use this as well, and do don't use size to fit)
CGSize textSize = [self.answer_text_label.text sizeWithFont:self.answer_text_label.font
constrainedToSize:CGSizeMake(self.answer_text_label.frame.size.width, MAXFLOAT)
lineBreakMode:self.answer_text_label.lineBreakMode];
self.answer_text_label.frame = CGRectMake(20.0f, 20.0f, textSize.width, textSize.height);
In iOS 6 and later, use NSLineBreakByWordWrapping, not UILineBreakModeWordWrap.
self.answer_text_label.lineBreakMode = NSLineBreakByWordWrapping;

Resources