确定UILabel可以使用的最大字符数 [英] determine the maximum number of characters a UILabel can take

查看:214
本文介绍了确定UILabel可以使用的最大字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定UILabel和NSString,如何确定UILabel中可以容纳多少字符串?我正在使用Xcode-5和iOS-7。

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.

我一直在试图看看我可以从线程计算UILabel文本大小但是我没有得到任何响应。

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.

推荐答案

嗯,我在这里所做的工作虽然可能有另一种更有效(但更不直接)的方式。

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

这产生:

您可以自行处理错误情况。例如,其余部分并不完全适合label2,它可能会更频繁地切换到单词的中间而不是。

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.

这篇关于确定UILabel可以使用的最大字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆