我有两个 UILabel,一个在另一个之上。 顶部的一个具有固定大小(2 行),底部的一个可以扩展(0 行)。 我用于标签的文本可能很短,有时可能很长。 如何计算第一个 UILabel 最大字符串长度而不在中间剪切一个单词?
//这是创建 2 个标签的代码。
titleView = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 200, 50)];
titleView.numberOfLines = 2;
titleView2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 250, 100)];
titleView2.numberOfLines = 0;
最佳答案
我已经用这个方法解决了这个问题:
+ (int)getSplitIndexWithString:(NSString *)str frame:(CGRect)frame andFont:(UIFont *)font
{
int length = 1;
int lastSpace = 1;
NSString *cutText = [str substringToIndex:length];
CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
while (textSize.height <= frame.size.height)
{
NSRange range = NSMakeRange (length, 1);
if ([[str substringWithRange:range] isEqualToString:@" "])
{
lastSpace = length;
}
length++;
cutText = [str substringToIndex:length];
textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
}
return lastSpace;
}
关于iphone - 如何计算 UILabel 可以包含的 NSString 最大长度而不截断文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9965474/