gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:57:00 24 4
gpt4 key购买 nike

我只想知道行数,给定字体、约束和文本。我可以在不创建 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com