隨著iOS 13的發(fā)布,公司的項(xiàng)目也勢(shì)必要著手適配了。現(xiàn)匯總一下iOS 13的各種坑
這次iOS 13系統(tǒng)升級(jí),影響范圍最廣的應(yīng)屬KVC訪問修改私有屬性了,直接禁止開發(fā)者獲取或直接設(shè)置私有屬性。而KVC的初衷是允許開發(fā)者通過Key名直接訪問修改對(duì)象的屬性值,為其中最典型的 UITextField 的 _placeholderLabel、UISearchBar 的 _searchField。
造成影響:在iOS 13下App閃退
錯(cuò)誤代碼:
// placeholderLabel私有屬性訪問[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];// searchField私有屬性訪問UISearchBar *searchBar = [[UISearchBar alloc] init];UITextField *searchTextField = [searchBar valueForKey:@"_searchField"];
解決方案:
使用 NSMutableAttributedString 富文本來替代KVC訪問 UITextField 的 _placeholderLabel
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"placeholder" attributes:@{NSForegroundColorAttributeName: [UIColor darkGrayColor], NSFontAttributeName: [UIFont systemFontOfSize:13]}];
因此,可以為UITextFeild創(chuàng)建Category,專門用于處理修改placeHolder屬性提供方法
#import "UITextField+ChangePlaceholder.h"@implementation UITextField (Change)- (void)setPlaceholderFont:(UIFont *)font { [self setPlaceholderColor:nil font:font];}- (void)setPlaceholderColor:(UIColor *)color { [self setPlaceholderColor:color font:nil];}- (void)setPlaceholderColor:(nullable UIColor *)color font:(nullable UIFont *)font { if ([self checkPlaceholderEmpty]) { return; } NSMutableAttributedString *placeholderAttriString = [[NSMutableAttributedString alloc] initWithString:self.placeholder]; if (color) { [placeholderAttriString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, self.placeholder.length)]; } if (font) { [placeholderAttriString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.placeholder.length)]; } [self setAttributedPlaceholder:placeholderAttriString];}- (BOOL)checkPlaceholderEmpty { return (self.placeholder == nil) || ([[self.placeholder stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0);}
關(guān)于 UISearchBar,可遍歷其所有子視圖,找到指定的 UITextField 類型的子視圖,再根據(jù)上述 UITextField 的通過富文本方法修改屬性。
#import "UISearchBar+ChangePrivateTextFieldSubview.h"@implementation UISearchBar (ChangePrivateTextFieldSubview)/// 修改SearchBar系統(tǒng)自帶的TextField- (void)changeSearchTextFieldWithCompletionBlock:(void(^)(UITextField *textField))completionBlock { if (!completionBlock) { return; } UITextField *textField = [self findTextFieldWithView:self]; if (textField) { completionBlock(textField); }}/// 遞歸遍歷UISearchBar的子視圖,找到UITextField- (UITextField *)findTextFieldWithView:(UIView *)view { for (UIView *subview in view.subviews) { if ([subview isKindOfClass:[UITextField class]]) { return (UITextField *)subview; }else if (subview.subviews.count > 0) { return [self findTextFieldWithView:subview]; } } return nil;}@end
PS:關(guān)于如何查找自己的App項(xiàng)目是否使用了私有api,可以參考iOS查找私有API 文章
模態(tài)彈窗屬性 UIModalPresentationStyle 在 iOS 13 下默認(rèn)被設(shè)置為 UIModalPresentationAutomatic新特性,展示樣式更為炫酷,同時(shí)可用下拉手勢(shì)關(guān)閉模態(tài)彈窗。
若原有模態(tài)彈出 ViewController 時(shí)都已指定模態(tài)彈窗屬性,則可以無視該改動(dòng)。
若想在 iOS 13 中繼續(xù)保持原有默認(rèn)模態(tài)彈窗效果??梢酝ㄟ^ runtime 的 Method Swizzling 方法交換來實(shí)現(xiàn)。
#import "UIViewController+ChangeDefaultPresentStyle.h"@implementation UIViewController (ChangeDefaultPresentStyle)+ (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Class class = [self class]; //替換方法 SEL originalSelector = @selector(presentViewController:animated:completion:); SEL newSelector = @selector(new_presentViewController:animated:completion:); Method originalMethod = class_getInstanceMethod(class, originalSelector); Method newMethod = class_getInstanceMethod(class, newSelector);; BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); if (didAddMethod) { class_replaceMethod(class, newSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, newMethod); } });}- (void)new_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion { viewControllerToPresent.modalPresentationStyle = UIModalPresentationFullScreen; [self new_presentViewController:viewControllerToPresent animated:flag completion:completion];}@end
針對(duì)黑暗模式的推出,Apple官方推薦所有三方App盡快適配。目前并沒有強(qiáng)制App進(jìn)行黑暗模式適配。因此黑暗模式適配范圍現(xiàn)在可采用以下三種策略:
3.1. 全局關(guān)閉黑暗模式
方案一:在項(xiàng)目 Info.plist 文件中,添加一條內(nèi)容,Key為 User Interface Style,值類型設(shè)置為String并設(shè)置為 Light 即可。
方案二:代碼強(qiáng)制關(guān)閉黑暗模式,將當(dāng)前 window 設(shè)置為 Light 狀態(tài)。
if(@available(iOS 13.0,*)){self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;}
3.2 指定頁面關(guān)閉黑暗模式
從Xcode 11、iOS 13開始,UIViewController與View新增屬性 overrideUserInterfaceStyle,若設(shè)置View對(duì)象該屬性為指定模式,則強(qiáng)制該對(duì)象以及子對(duì)象以指定模式展示,不會(huì)跟隨系統(tǒng)模式改變。
3.3 全局適配黑暗模式
配黑暗模式,主要從兩方面入手:圖片資源適配與顏色適配
圖片資源適配
打開圖片資源管理庫 Assets.xcassets,選中需要適配的圖片素材item,打開最右側(cè)的 Inspectors 工具欄,找到 Appearances 選項(xiàng),并設(shè)置為 Any, Dark模式,此時(shí)會(huì)在item下增加Dark Appearance,將黑暗模式下的素材拖入即可。關(guān)于黑暗模式圖片資源的加載,與正常加載圖片方法一致。
顏色適配
iOS 13開始UIColor變?yōu)閯?dòng)態(tài)顏色,在Light Mode與Dark Mode可以分別設(shè)置不同顏色。若UIColor色值管理,與圖片資源一樣存儲(chǔ)于 Assets.xcassets 中,同樣參照上述方法適配。若UIColor色值并沒有存儲(chǔ)于 Assets.xcassets 情況下,自定義動(dòng)態(tài)UIColor時(shí),在iOS 13下初始化方法增加了兩個(gè)方法
+ (UIColor *)colorWithDynamicProvider:(UIColor * (^)(UITraitCollection *))dynamicProvider API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);- (UIColor *)initWithDynamicProvider:(UIColor * (^)(UITraitCollection *))dynamicProvider API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);
這兩個(gè)方法要求傳一個(gè)block,block會(huì)返回一個(gè) UITraitCollection 類
當(dāng)系統(tǒng)在黑暗模式與正常模式切換時(shí),會(huì)觸發(fā)block回調(diào)
示例代碼:
UIColor *dynamicColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull trainCollection) { if ([trainCollection userInterfaceStyle] == UIUserInterfaceStyleLight) { return [UIColor whiteColor]; } else { return [UIColor blackColor]; } }]; [self.view setBackgroundColor:dynamicColor];
當(dāng)然了,iOS 13系統(tǒng)也默認(rèn)提供了一套基本的黑暗模式UIColor動(dòng)態(tài)顏色,具體聲明如下:
@property (class, nonatomic, readonly) UIColor *systemBrownColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *systemIndigoColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *systemGray2Color API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *systemGray3Color API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *systemGray4Color API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *systemGray5Color API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *systemGray6Color API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *labelColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *secondaryLabelColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *tertiaryLabelColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *quaternaryLabelColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *linkColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *placeholderTextColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *separatorColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *opaqueSeparatorColor API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);@property (class, nonatomic, readonly) UIColor *systemBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *secondarySystemBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *tertiarySystemBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *systemGroupedBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *secondarySystemGroupedBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *tertiarySystemGroupedBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *systemFillColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *secondarySystemFillColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *tertiarySystemFillColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);@property (class, nonatomic, readonly) UIColor *quaternarySystemFillColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos, watchos);
監(jiān)聽模式的切換
當(dāng)需要監(jiān)聽系統(tǒng)模式發(fā)生變化并作出響應(yīng)時(shí),需要用到 ViewController 以下函數(shù)
// 注意:參數(shù)為變化前的traitCollection,改函數(shù)需要重寫- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection; // 判斷兩個(gè)UITraitCollection對(duì)象是否不同- (BOOL)hasDifferentColorAppearanceComparedToTraitCollection:(UITraitCollection *)traitCollection;
示例代碼:
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; // trait has Changed? if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) { // do something... } }
系統(tǒng)模式變更,自定義重繪視圖
當(dāng)系統(tǒng)模式變更時(shí),系統(tǒng)會(huì)通知所有的 View以及 ViewController 需要更新樣式,會(huì)觸發(fā)以下方法執(zhí)行(參考Apple官方適配鏈接):
NSView
- (void)updateLayer;- (void)drawRect:(NSRect)dirtyRect;- (void)layout;- (void)updateConstraints;
UIView
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection;- (void)layoutSubviews;- (void)drawRect:(NSRect)dirtyRect;- (void)updateConstraints;- (void)tintColorDidChange;
UIViewController
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection;- (void)updateViewConstraints;- (void)viewWillLayoutSubviews;- (void)viewDidLayoutSubviews;
UIPresentationController
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection;- (void)containerViewWillLayoutSubviews;- (void)containerViewDidLayoutSubviews;
使用 LaunchImage 設(shè)置啟動(dòng)圖,需要提供各類屏幕尺寸的啟動(dòng)圖適配,這種方式隨著各類設(shè)備尺寸的增加,增加了額外不必要的工作量。為了解決 LaunchImage 帶來的弊端,iOS 8引入了 LaunchScreen 技術(shù),因?yàn)橹С?AutoLayout + SizeClass,所以通過 LaunchScreen 就可以簡單解決適配當(dāng)下以及未來各種屏幕尺寸。
Apple官方已經(jīng)發(fā)出公告,2020年4月開始,所有使用iOS 13 SDK 的App都必須提供 LaunchScreen。創(chuàng)建一個(gè) LaunchScreen 也非常簡單
(1)New Files創(chuàng)建一個(gè) LaunchScreen,在創(chuàng)建的 ViewController 下 View 中新建一個(gè) Image,并配置 Image 的圖片
(2)調(diào)整 Image 的 frame 為占滿屏幕,并修改 Image 的 Autoresizing 如下圖,完成
在iOS13之前,無需權(quán)限提示窗即可直接使用藍(lán)牙,但在iOS 13下,新增了使用藍(lán)牙的權(quán)限申請(qǐng)。最近一段時(shí)間上傳IPA包至App Store會(huì)收到以下提示。
解決方案:只需要在 Info.plist 里增加以下條目:
<key>NSBluetoothAlwaysUsageDescription</key> <string>這里輸入使用藍(lán)牙來做什么</string>`
在iOS 13系統(tǒng)中,Apple要求提供第三方登錄的App也要支持「Sign With Apple」,具體實(shí)踐參考 iOS Sign With Apple實(shí)踐
在iOS 13之前,獲取Device Token 是將系統(tǒng)返回的 NSData 類型數(shù)據(jù)通過 -(void)description; 方法直接轉(zhuǎn)換成 NSString 字符串。
iOS 13之前獲取結(jié)果:
iOS 13之后獲取結(jié)果:
適配方案:目的是要將系統(tǒng)返回 NSData 類型數(shù)據(jù)轉(zhuǎn)換成字符串,再傳給推送服務(wù)方。-(void)description; 本身是用于為類調(diào)試提供相關(guān)的打印信息,嚴(yán)格來說,不應(yīng)直接從該方法獲取數(shù)據(jù)并應(yīng)用于正式環(huán)境中。將 NSData 轉(zhuǎn)換成 HexString,即可滿足適配需求。
- (NSString *)getHexStringForData:(NSData *)data { NSUInteger length = [data length]; char *chars = (char *)[data bytes]; NSMutableString *hexString = [[NSMutableString alloc] init]; for (NSUInteger i = 0; i < length; i++) { [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", chars[i]]]; } return hexString;}
主要還是參照了Apple官方的 UIKit 修改文檔聲明。iOS 13 Release Notes
8.1. UITableView
iOS 13下設(shè)置 cell.contentView.backgroundColor 會(huì)直接影響 cell 本身 selected 與 highlighted 效果。建議不要對(duì) contentView.backgroundColor 修改,而對(duì) cell 本身進(jìn)行設(shè)置。
8.2. UITabbar
Badge 文字大小變化
iOS 13之后,Badge 字體默認(rèn)由13號(hào)變?yōu)?7號(hào)。建議在初始化 TabbarController 時(shí),顯示 Badge 的 ViewController 調(diào)用 setBadgeTextAttributes:forState: 方法
if (@available(iOS 13, *)) { [viewController.tabBarItem setBadgeTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13]} forState:UIControlStateNormal]; [viewController.tabBarItem setBadgeTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13]} forState:UIControlStateSelected];}
8.2. UITabBarItem
加載gif需設(shè)置 scale 比例
NSData *data = [NSData dataWithContentsOfFile:path];CGImageSourceRef gifSource = CGImageSourceCreateWithData(CFBridgingRetain(data), nil);size_t gifCount = CGImageSourceGetCount(gifSource);CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i,NULL);// iOS 13之前UIImage *image = [UIImage imageWithCGImage:imageRef]// iOS 13之后添加scale比例(該imageView將展示該動(dòng)圖效果)UIImage *image = [UIImage imageWithCGImage:imageRef scale:image.size.width / CGRectGetWidth(imageView.frame) orientation:UIImageOrientationUp];CGImageRelease(imageRef);
無文字時(shí)圖片位置調(diào)整
iOS 13下不需要調(diào)整 imageInsets,圖片會(huì)自動(dòng)居中顯示,因此只需要針對(duì)iOS 13之前的做適配即可。
if (IOS_VERSION < 13.0) { viewController.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0); }
8.3. 新增 Diffable DataSource
在 iOS 13下,對(duì) UITableView 與 UICollectionView 新增了一套 Diffable DataSource API。為了更高效地更新數(shù)據(jù)源刷新列表,避免了原有粗暴的刷新方法 - (void)reloadData,以及手動(dòng)調(diào)用控制列表刷新范圍的api,很容易出現(xiàn)計(jì)算不準(zhǔn)確造成 NSInternalInconsistencyException 而引發(fā)App crash。
api 官方鏈接
StatusBar 新增一種樣式,默認(rèn)的 default 由之前的黑色字體,變?yōu)楦鶕?jù)系統(tǒng)模式自動(dòng)選擇展示 lightContent 或者 darkContent
針對(duì)iOS 13 SDK適配,后續(xù)將會(huì)持續(xù)收集并更新
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選