Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

ios - determine the maximum number of characters a UILabel can take

Given a UILabel and a NSString, how do I determine how much of the string can fit inside the UILabel? I am using Xcode-5 and iOS-7.

I have been trying to see what I can extract from the thread Calculating UILabel Text Size but I am not getting anywhere with the responses there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, what I did here works though there may be another, more efficient (yet less straight-forward) way.

What I did was just calculate the size of the rect needed for the text, see if it fits in the label's frame, and if not, chop off a character and try again.

@interface LTViewController ()

@property (nonatomic, weak) IBOutlet UILabel *label1;
@property (nonatomic, weak) IBOutlet UILabel *label2;

@end

@implementation LTViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILabel *label1 = self.label1;
    UILabel *label2 = self.label2;

    UIFont *font = label1.font;
    NSString *text = @"This is some text that will go into labels 1 and 2.";

    CGRect label1Frame = label1.frame;

    NSUInteger numberOfCharsInLabel1 = NSNotFound;

    for (int i = [text length]; i >= 0; i--) {
        NSString *substring = [text substringToIndex:i];
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:substring
                                                                             attributes:@{ NSFontAttributeName : font }];
        CGSize size = CGSizeMake(label1Frame.size.width, CGFLOAT_MAX);
        CGRect textFrame = [attributedText boundingRectWithSize:size
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                        context:nil];

        if (CGRectGetHeight(textFrame) <= CGRectGetHeight(label1Frame)) {
            numberOfCharsInLabel1 = i;
            break;
        }
    }

    if (numberOfCharsInLabel1 == NSNotFound) {
        // TODO: Handle this case.
    }

    label1.text = [text substringToIndex:numberOfCharsInLabel1];
    label2.text = [text substringWithRange:NSMakeRange(numberOfCharsInLabel1, [text length] - numberOfCharsInLabel1)];
}

@end

This yields:

screen shot

It's up to you to handle the error conditions. For example, the rest doesn't completely fit into label2 and it's probably going to chop in the middle of a word more often then not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...