標籤:log code turned 電腦 大小 nslog amount space ios
設計師給到的圖,經常是 “按鈕的左邊距離文字右邊5px” 這樣子的標註。於是我們需要計算文字的寬度。
有兩種方法:
-
用 label 或 button 的 sizetofit 方法
[label sizeToFit];NSLog(@"label size is %@",[NSValue valueWithCGSize:label.bounds.size]);
-
用 sizeWithAttributes方法
CGSize size = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];NSLog(@"size WithAttributes is %@",[NSValue valueWithCGSize:size]);
結果如何呢?
label size is NSSize: {96.5, 20.5}
size WithAttributes is NSSize: {96.39697265625, 20.287109375}
可見兩個傳回值不同,第二種方法返回的值似乎精確,應該用哪個呢?
我們來看下文檔怎麼說的。
-
關於 sizeWithAttributes 的文檔
This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function.
-
關於 sizeToFit 的文檔
Call this method when you want to resize the current view so that it uses the most appropriate amount of space.
在文檔中,明確指出了使用 sizeWithAttributes 時,需要使用 ceil 方法取整。而 sizeToFit 方法會當前 view 的大小調整為 appropriate 大小。
這裡的關鍵是對 appropriate 的理解。我說下我的理解,至少應該滿足兩個條件:
- 不截斷
就是說返回的值應該不小於文字的寬度/長度,否則會被截斷。
- 像素對齊
所有的 view 的起始和結束為止都應該在物理像素上。因此在 @2x 螢幕應該返回 0.5 的整數倍,在 @1x 螢幕上應該返回 1 的整數倍。
因此應該用第二種方法,或者把第一種方法的結果向上取整。
如果直接使用第一種方法的結果,會導致其他介面像素對不齊,有奇怪的表現。
想象一下電腦如何處理 “一條線段,起點是 3.452 像素,終點是 56.341 像素” 這種奇怪的東西。
iOS 計算文字寬度的一個細節