您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 7 開發中那些被標記為 Deprecated 的寫法該怎麼改

編輯:iOS 開發綜合

從 iOS 6 升級到 iOS 7,編譯器會冒出一堆黃底警告。這些 deprecated 標記不代表現在不能用,但代表遲早會被移除。以下整理幾個最常見的替換寫法。

一、文字對齊常數改名

// 舊寫法
cell.textLabel.textAlignment = UITextAlignmentCenter;

// 新寫法
cell.textLabel.textAlignment = NSTextAlignmentCenter;

UITextAlignment 系列整批被 NSTextAlignment 取代,命名從「UIText」改成更明確的「NSText」,這也與 NSString 的 drawing 系列 API 保持一致。

二、Cell 的初始化方式

// 舊寫法(且使用了 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。

三、Modal 呈現加入 completion

// 舊寫法
[self presentModalViewController:calendarView animated:YES];

// 新寫法
[self presentViewController:calendarView animated:YES completion:^{
    // 呈現動畫結束後才執行
}];

新介面多了一個 completion 參數,允許傳入一個 Block。這個 Block 的執行時機是在 viewDidAppear 之後,也就是「畫面確實已經出現在使用者眼前」的那一刻。這帶來一個實作上的好處:多個 UI 效果之間的銜接與轉換可以精確排序,不必再用 dispatch_after 猜時間。

四、UIPageControl 的子視圖型別變了

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 做型別判斷再分流的寫法,讓同一份程式碼能同時支援舊版與新版,是處理這類系統差異最保守也最可靠的方式。

五、文字繪製改用 Attributes

#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 中重新布局。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved