简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM