字體大小動態變化
在使用UIbutton,UIlabel等控件時,我們經常需要設置字體大小,設置字體就需要用到UIFont類,平時在使用文本字體時,多數情況下是確定的字體,確定的字號,這些情況是沒有內存問題的。但是在一些情況下,我們需要動態改變字體大小,比如說,一個frame動態變化的按鈕,字體大小需要隨著frame的變化而變化。這種情況似乎使用adjustsFontSizeToFitWidth屬性比較好,實際上adjustsFontSizeToFitWidth只會讓字體縮小,不能變大。
fontWithSize和systemFontOfSize使用注意
?fontWithSize和systemFontOfSize可以設置字體大小,可以在按鈕的frame變化的時候,用這兩個方法更新字體大小。這兩個方法都是新建一個UIFont對象,指定大小后返回。打開UIFont.h,可以找到:
// Some convenience methods to create system fonts
// Think carefully before using these methods. In most cases, a font returned by +preferredFontForTextStyle: will be more appropriate, and will respect the user's selected content size category.
+ (UIFont*)systemFontOfSize:(CGFloat)fontSize;
+ (UIFont*)boldSystemFontOfSize:(CGFloat)fontSize;
+ (UIFont*)italicSystemFontOfSize:(CGFloat)fontSize;
// Create a new font that is identical to the current font except the specified size
- (UIFont*)fontWithSize:(CGFloat)fontSize;
類似于imageNamed,這兩種方法也有緩存機制:
You do not create UIFont objects using the alloc and init methods. Instead, you use class methods of UIFont to look up and retrieve the desired font object. These methods check for an existing font object with the specified characteristics and return it if it exists. Otherwise, they create a new font object based on the desired font characteristics.
這就意味著每次設置字體大小的時候,會新建一個UIFont對象,設置字號后返回,而且舊值會緩存起來,以備下次查找使用,在一些動畫場景,frame的大小是連續變化的,字號類型是CGFloat,那么可能的值就會有很多種(比如0.0001,0.0002...),這種情況緩存機制就會使內存一直增加。舉個例子,在我的程序中,有個滑動頁面,頁面滑動的時候,導航的字體根據滑動幅度從20變化到40,這樣幾乎每次滑動頁面,內存就會上漲3M,這是非常嚴重的。
解決方法
解決方法其實就是限制緩存的數量,以20到40為例,分成固定數目的狀態,比如20,21,22,..., 40。這樣緩存大小就固定了,不會每次滑動就產生新的緩存。