如果我有字符串“Life is Good”。现在我需要从符合宽度40的字符串中提取一些单词。如何从目标C中实现这一点?
答案 0 :(得分:1)
您可以在循环中使用sizeWithFont:
方法,如下所示:
NSString *longestFitting = nil;
NSString *orig = "Life is Good";
UIFont *font = ...;
for (int i = orig.length-1 ; i > 1 ; i--) {
NSString *tmp = [orig substringToIndex:i];
if ([tmp sizeWithFont:font].width <= 40) {
longestFitting = tmp;
break;
}
}
答案 1 :(得分:1)
你的答案是正确的但是要完全符合40我已经纠正&lt; = to ==所以新代码将是
NSString *longestFitting = nil;
NSString *orig = "Life is Good";
UIFont *font = ...;
for (int i = orig.length-1 ; i > 1 ; i--)
{
NSString *tmp = [orig substringToIndex:i];
if ([tmp sizeWithFont:font].width == 40)
{
longestFitting = tmp;
break;
}
}