Reputation: 3301
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..
Upvotes: 2
Views: 9938
Reputation:
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];
}
}
Upvotes: 8
Reputation: 10172
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
Upvotes: 0
Reputation: 2145
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
Upvotes: 2
Reputation: 9913
Yes you can use :
your_text = [your_text substringToIndex:10];
your_label.text = your_text;
Hope it helps you.
Upvotes: 2
Reputation: 3901
NSString *temp = your string;
if ([temp length] > 10) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 10}];
temp = [temp substringWithRange:range];
}
coverView.label2.text = temp;
Upvotes: 1