從 iOS 6 升級到 iOS 7,編譯器會冒出一堆黃底警告。這些 deprecated 標記不代表現在不能用,但代表遲早會被移除。以下整理幾個最常見的替換寫法。
// 舊寫法 cell.textLabel.textAlignment = UITextAlignmentCenter; // 新寫法 cell.textLabel.textAlignment = NSTextAlignmentCenter;
UITextAlignment 系列整批被 NSTextAlignment 取代,命名從「UIText」改成更明確的「NSText」,這也與 NSString 的 drawing 系列 API 保持一致。
// 舊寫法(且使用了 MRC 的 autorelease)
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:nil] autorelease];
// 新寫法
static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
UITableViewCell *cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:TableSampleIdentifier];
改用 initWithStyle:reuseIdentifier: 之後,才能使用 textLabel、detailTextLabel、imageView 這些內建子元件,也才能享受系統的重用機制。ARC 之下更不需要 autorelease。
// 舊寫法
[self presentModalViewController:calendarView animated:YES];
// 新寫法
[self presentViewController:calendarView animated:YES completion:^{
// 呈現動畫結束後才執行
}];
新介面多了一個 completion 參數,允許傳入一個 Block。這個 Block 的執行時機是在 viewDidAppear 之後,也就是「畫面確實已經出現在使用者眼前」的那一刻。這帶來一個實作上的好處:多個 UI 效果之間的銜接與轉換可以精確排序,不必再用 dispatch_after 猜時間。
iOS 7 中,[self.subviews objectAtIndex:i] 取出來的已經不是 UIImageView,而是 UIView。因此原本靠 dot.image = ... 更換圓點圖片的寫法會失效,必須改用 backgroundColor 搭配 patternImage。
- (void)updateDots {
for (int i = 0; i < [self.subviews count]; i++) {
UIView *dotView = [self.subviews objectAtIndex:i];
if ([dotView isKindOfClass:[UIImageView class]]) {
UIImageView *dot = (UIImageView *)dotView;
dot.image = (i == self.currentPage) ? _activeImage : _inactiveImage;
} else {
// iOS 7 之後走這一支
UIImage *img = (i == self.currentPage) ? _activeImage : _inactiveImage;
[dotView setBackgroundColor:[UIColor colorWithPatternImage:img]];
}
}
}
用 isKindOfClass 做型別判斷再分流的寫法,讓同一份程式碼能同時支援舊版與新版,是處理這類系統差異最保守也最可靠的方式。
#define NLSystemVersionGreaterOrEqualThan(version) \
([[[UIDevice currentDevice] systemVersion] floatValue] >= version)
#define IOS7_OR_LATER NLSystemVersionGreaterOrEqualThan(7.0)
if (IOS7_OR_LATER) {
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
font = [font fontWithSize:14.0f];
[text drawAtPoint:textPt withAttributes:@{NSFontAttributeName: font}];
} else {
[text drawAtPoint:textPt withFont:[UIFont systemFontOfSize:14.0f]];
}
withFont: 這類單一屬性的繪製方法已被 withAttributes: 取代。改用字典傳參之後,可以同時指定字型、顏色、段落樣式、字距與底線,擴充性遠勝以往。
順帶一提,這裡的 UIFontTextStyleBody 屬於 Dynamic Type 體系。若你的 App 希望支援使用者在系統設定中調整字級,就應該直接使用 preferredFontForTextStyle 而不覆寫 size,並在 contentSizeCategoryDidChangeNotification 中重新布局。