iOS7.0中UILabel高度調整注意事項

來源:互聯網
上載者:User

標籤:

轉自: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高度調整注意事項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.