ios - 我可以在不创建 UILabel 的情况下计算出 NSString 的 numberOfLines 吗?

标签 ios iphone objective-c nsstring

我只想知道行数,给定字体、约束和文本。我可以在不创建 UILabel 的情况下解决这个问题吗?

+ (int)numberOfLines:(NSDictionary *)data{
    NSString *myString = [some string calculation];
    CGSize sizeConstrain = CGSizeMake(some constrain calculation);
    CGSize stringSize = [myString sizeWithFont:someFont constrainedToSize:sizeConstrain];

    CGRect labelFrame = CGRectMake(0,
                                   0,
                                   stringSize.width,
                                   stringSize.height + 2);

    UILabel *label = [[UILabel alloc]initWithFrame:labelFrame];

    label.text = myString;
    return label.numberOfLines;
}

最佳答案

+ (int)numberOfLines:(NSDictionary *)data{
        NSString *myString = [some string calculation];
        CGSize sizeConstrain = CGSizeMake(some constrain calculation);
        CGSize stringSize = [myString sizeWithFont:someFont constrainedToSize:sizeConstrain];


        return (stringSize.height/someFont.lineHeight);
    }

编辑:我将其用于 UITextView 和 iOS7

 - (CGFloat) getRowsForText:(NSString*) text{

CGFloat fixedWidth = 300;

UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:14];
NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
paragrapStyle.alignment = NSTextAlignmentLeft;

textStepAttr = [NSDictionary dictionaryWithObjectsAndKeys:
                font,NSFontAttributeName,
                paragrapStyle, NSParagraphStyleAttributeName,
                nil];

NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:textStepAttr];
CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(fixedWidth, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];


return (rect.size.height / font.lineHeight) ;
}

关于ios - 我可以在不创建 UILabel 的情况下计算出 NSString 的 numberOfLines 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22300016/

相关文章:

ios - 如何在 SKScene 中引用我的 UIViewController?

iphone - 如何从我的 iOS 应用程序向 Mac 应用程序发送 MIDI 或 OSC 信号?

iphone - 如何在 iOS 中释放 subview

objective-c - 将 NSMutableArray 写入文件并将其加载回来

objective-c - NSScreen的可见框太大

ios - 如何弱引用作为参数传递的函数

iphone - 如果我对在 VMware 上运行的 OS X 感到满意,我真的必须购买 Mac 才能为 App Store 开发吗?

ios - 在 swift 中为 Ui Collection View 创建一个 Arc

Objective-C - 在执行 "Initializer Chain"后遇到问题

iphone - 加载 xib 文件