我可以在不创建UILabel的情况下找出NSString的numberOfLines吗?

时间:2014-03-10 12:23:09

标签: 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;
}

1 个答案:

答案 0 :(得分:3)

+ (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) ;
}