2012-07-18 75 views

回答

1

你的答案是正確的,但以適應確切40我已經改正了< =到==這樣新的代碼將是

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

您可以在循環使用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; 
    } 
} 
+0

你的答案是正確的,但要適合確切的40我已經糾正一個<=爲==所以新的代碼將是 NSString * longestFitting = nil; NSString * orig =「生活是美好的」; UIFont * font = ...; (int i = orig.length-1; i> 1; i--){ NSString * tmp = [orig substringToIndex:i]; ([tmp sizeWithFont:font] .width == 40){ longestFitting = tmp; 休息; } } – shrestha2lt8 2012-07-18 12:10:33

+0

@ shrestha2lt8有一個機會,你不會找到一個確切的長度:'生命是'可能是42,'生活我'可能是38. – dasblinkenlight 2012-07-18 12:18:58

+0

感謝您的解決方案。除非在iOS 7中不推薦使用'sizeWithFont:',否則請使用'[tmp sizeWithAttributes:@ {NSFontAttributeName:font}]''。 – anneblue 2014-07-24 14:28:14