How to limit UILabel text length - IOS - iphone

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

Related

How to bring to front a programmatically generated UILabel in a UITableView, in Swift

I have a programmatically generated UITableView with many UILabel's.
Each added UILabel should be seen in front.
All works ok until I add the final UILabel, which appears behind all the others.
How can I bring it to the front?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
if (cell == nil)
{
if( dbg ) NSLog( #" - cell nil");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
/* Though it's UITableViewCellStyleDefault, the three defaults (image, label, detail label) are nil
if not set. */
// UI controls must be preset for re-used, to prevent memory leak:
// Allocate max. possible UI controls for this row, once per boot:
int instance;
for( instance=0; instance < MAX_CELL_UILABEL; ++instance )
{
UILabel* cell_UILabel = [[UILabel alloc] initWithFrame: CGRectZero]; // allocate next UI control
[cell.contentView addSubview: cell_UILabel ]; // add it permanently to the cell
cell_UILabel.tag = BASE_UILABEL_TAG + instance; // assign unique ID for later lookup
}
...
OTHER UILABELS ARE ADDED HERE.
AND, HERE IS THE FINAL UILABEL, WHICH APPEARS BEHIND THE REST, WHEN IT SHOULD APPEAR IN FRONT:
UILabel* battery_percent = (UILabel*)[cell.contentView viewWithTag: BASE_UILABEL_TAG + ul++];
battery_percent.frame = CGRectMake (x,y, w,h);
battery_percent.backgroundColor = [UIColor orangeColor];
battery_percent.textAlignment = NSTextAlignmentCenter; // NSTextAlignmentRight, NSTextAlignmentLeft
battery_percent.font = [UIFont systemFontOfSize: font_size];
battery_percent.textColor=[UIColor whiteColor];
battery_percent.numberOfLines=0;
// Show battery %:
battery_percent.text = [NSString stringWithFormat: #"%d%%", battery_charge_percent ];
[cell bringSubviewToFront:label];
I found the answer elsewhere on Stackoverflow:
[cell.contentView bringSubviewToFront: battery_percent];
Sweet!
From
int instance;
for( instance=0; instance < MAX_CELL_UILABEL; ++instance )
{
UILabel* cell_UILabel = [[UILabel alloc] initWithFrame: CGRectZero]; // allocate next UI control
[cell.contentView addSubview: cell_UILabel ]; // add it permanently to the cell
cell_UILabel.tag = BASE_UILABEL_TAG + instance; // assign unique ID for later lookup
}
The battery_percent label should have a tag value of (BASE_UILABEL_TAG + MAX_CELL_UILABEL - 1)
When you grab the battery_percent label later on with
UILabel* battery_percent = (UILabel*)[cell.contentView viewWithTag: BASE_UILABEL_TAG + ul++];
What is the value of ul at this point?
If it isn't equivalent to (MAX_CELL_UILABEL - 1) then you're grabbing the wrong label.
Here I am not sure where you are adding the battery_percent label...either cell or cell.contentView
So I would suggest you to Use this.
[[battery_percent superView] bringSubviewToFront:battery_percent];
Hope this will help you.

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

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.

Adding an uneditable text suffix to a UITextField

I have a UITextField that I'd like to add a "?" suffix to all text entered.
The user should not be able to remove this "?" or add text to the right hand side of it.
What's the best way to go about this?
Use the UITextFieldDelegate protocol to alter the string whenever the field is being edited. Here's a quick stab at it; this will need work, but it should get you started.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * currentText = [textField text];
if( [currentText characterAtIndex:[currentText length] - 1] != '?' ){
NSMutableString * newText = [NSMutableString stringWithString:currentText];
[newText replaceCharactersInRange:range withString:string];
[newText appendString:#"?"];
[textField setText:newText];
// We've already made the replacement
return NO;
}
// Allow the text field to handle the replacement
return YES;
}
You'll probably need to subclass UITextField and override its drawText: method to draw an additional "?" character to the right of the actual text. (Rather than actually add a "?" to the text of the view.
I had this issue and I wrote a subclass to add this functionality: https://github.com/sbaumgarten/UIPlaceholderSuffixField.
Hopefully you have found a solution by now but if you haven't, this should work.
I realize this answer is late, but I found most of these did not work for my scenario. I have a UITextField that I simply want to force to have a suffix that the user cannot edit. However, I don't want to subclass UITextView, modify how it handles drawing, etc. I just want to prevent the user from modifying the suffix.
First, I ensure the suffix is set in the textfield when editing takes place. This could be done any number of ways depending upon your scenario. For mine, I wanted it there from the start, so I simply set the textfield's text property equal to the suffix when the view loads and store off the length of the suffix for later. For example:
- (void)viewDidLoad {
[super viewDidLoad];
myTextField.text = "suffix";
_suffixLength = myTextField.text.length;
}
Then I used the UITextFieldDelegate protocol as Josh suggested above, but use the length of the string and the range to ensure nothing edits the suffix:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Determine starting location of the suffix in the current string
int suffixLocation = textField.text.length - _suffixLength;
// Do not allow replacing anything in/past the suffix
if (range.location + range.length > suffixLocation)
{
return NO;
}
// Continue with delegate code...
}
This should work for any suffix value you assign to the textfield.
For a single-line UITextField you should be able to measure the size of the NSString (it has a measurement function in there, somewhere) and move a UILabel to the right position.
I would add a method that is called when edit finishes:
`- (void)editDidFinish {
NSString* str=[[NSString alloc] init];
str=myEdit.text;
[str stringByAppendingString:#"?"];
myEdit.text=str;
}`
OK, im definitly too late, but maybe i can help someone out either way:
The intended way to accomplish this is by using a custom NSFormatter. Heres the docs:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/Reference/Reference.html
The basic idea is this: you create a subclass of NSFormatter, and the override at least the two worker methods:
-stringObjectForValue:
this will produce the dipsplay-String from the value stored in the object (i.e. add your questionmark here)
-objectValue:ForString:errorDescription
here, you need to transform the display-string into an object you want to store, i.e. remove the questionmark
The formatter can then be used to convert the data from the stored objects into strings that are suitable for presentation to the user.
The big advantage is that you can use formatters wherever your string will appear in the UI. It is not limited to certain UI-Elements like the solution where you override -drawText in UITextField. Its just hella convenient.
This class method I have written in Objective-C, helps you to add a suffix text to a UITextField.
I order to make it work, you need to initialize the UILabel to the prefix or suffix in your UITextFieldLabel as follow:
myTextField.rightView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, myTextField.frame.size.height)];
myTextField.rightViewMode = UITextFieldViewModeAlways;
[MyClass UpdateUITextFieldSuffix:myTextField withString:#"My Suffix!"];
Once we have the UILabel attached to the UITextField, you can use this class method to update the text, and this text will be automatically resized to fit in the field.
+ (BOOL)UpdateUITextFieldSuffix:(UITextField*)textField withString:(NSString*)string
{
BOOL returnUpdateSuffix = NO;
if (string != nil && [string respondsToSelector:#selector(length)] && [string length] > 0)
{
NSObject *labelSuffix = textField.rightView;
if (labelSuffix != nil && [labelSuffix respondsToSelector:#selector(setText:)])
{
[(UILabel*)labelSuffix setTextAlignment:NSTextAlignmentRight];
[(UILabel*)labelSuffix setText:string];
[(UILabel*)labelSuffix setBackgroundColor:[UIColor redColor]];
{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
((UILabel*)labelSuffix).font, NSFontAttributeName,nil];
CGRect frame = [((UILabel*)labelSuffix).text boundingRectWithSize:CGSizeMake(0.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
CGRect newFrame = [(UILabel*)labelSuffix frame];
newFrame.size.width = size.width;
[(UILabel*)labelSuffix setFrame:newFrame];
[(UILabel*)labelSuffix setNeedsLayout];
[(UILabel*)labelSuffix layoutIfNeeded];
}
returnUpdateSuffix = YES;
}
}
return returnUpdateSuffix;
}
I have written the following method to achieve the above task of placing non-editable suffix to UITextField:
- (void)setSuffixText:(NSString *)suffix
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setBackgroundColor:[UIColor clearColor]];
[label setFont:[UIFont fontWithName:self.tfdDistance.font.fontName size:self.tfdDistance.font.pointSize]];
[label setTextColor:self.tfdDistance.textColor];
[label setAlpha:.5];
[label setText:suffix];
CGSize suffixSize = [suffix sizeWithFont:label.font];
label.frame = CGRectMake(0, 0, suffixSize.width, self.tfdDistance.frame.size.height);
[self.tfdDistance setRightView:label];
[self.tfdDistance setRightViewMode:UITextFieldViewModeAlways];
}​

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