標籤:
轉自:http://blog.csdn.net/k12104/article/details/33731833
http://herkuang.info/blog/2013/12/31/ios7%E4%B8%ADuilabel%E9%AB%98%E5%BA%A6%E8%B0%83%E6%95%B4%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9/
我的“記詞助手”在升級到iOS7之後,一直出現UILabel錯位的問題:
我的label是用- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode 來計算的,但是似乎計算得不是很正確。
實際上UILabel的frame是紅框的大小,但是在寬度不夠的時候,不知道觸發了什麼bug,這個Label在繪製的時候文字會被擠下去。這個問題到底是什麼,我也沒搞清楚,但是增加UILabel的寬度後,就會顯示正常。
在跟了一遍代碼後發現,在iOS7下面,- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode這個函數返回的值是帶小數的,設給UILabel的frame之後,UILabel的寬度就小於文字繪製需要的寬度了。就會造成上面的問題。
在官方文檔裡可以看到,- (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.
也就是說,計算出的size需要用ceil函數取整。
在iOS7中,正確地計算UILabel可能佔有的高度需要如下的步驟:
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);
iOS7.0中UILabel高度調整注意事項