註釋:原文連接丟失。ios
個人「記詞助手」在升級到iOS7以後,一直出現UILabel錯位的問題:app
個人label是用- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode 來計算的,可是彷佛計算得不是很正確。函數
實際上UILabel的frame是紅框的大小,可是在寬度不夠的時候,不知道觸發了什麼bug,這個Label在繪製的時候文字會被擠下去。這個問題究竟是什麼,我也沒搞清楚,可是增長UILabel的寬度後,就會顯示正常。rest
在跟了一遍代碼後發現,在iOS7下面,- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode這個函數返回的值是帶小數的,設給UILabel的frame以後,UILabel的寬度就小於文字繪製須要的寬度了。就會形成上面的問題。component
在官方文檔裏能夠看到,- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode這個函數在iOS7裏面已經deprecated了,取而代之的是boundingRectWithSize:options:attributes:context:這個函數。實際上這兩個函數在iOS7裏面的計算結果是一致的,都是帶小數的。boundingRectWithSize:options:attributes:context:的文檔中能夠看到這麼一句話:文檔
This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.get
也就是說,計算出的size須要用ceil函數取整。it
在iOS7中,正確地計算UILabel可能佔有的高度須要以下的步驟:io
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:someFont, NSParagraphStyleAttributeName:paragraphStyle.copy};
labelSize = [someText boundingRectWithSize:CGSizeMake(207, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
/*
This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.
*/
labelSize.height = ceil(labelSize.height);
labelSize.width = ceil(labelSize.width);table