iOS13原生端适配攻略(推荐)

随着iOS 13的发布,公司的项目也势必要着手适配了。现汇总一下iOS 13的各种坑

1. KVC访问私有属性

这次iOS 13系统升级,影响范围最广的应属KVC访问修改私有属性了,直接禁止开发者获取或直接设置私有属性。而KVC的初衷是允许开发者通过Key名直接访问修改对象的属性值,为其中最典型的 UITextField 的 _placeholderLabel、UISearchBar 的 _searchField。

造成影响:在iOS 13下App闪退

错误代码:

// 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创建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);
}

关于 UISearchBar,可遍历其所有子视图,找到指定的 UITextField 类型的子视图,再根据上述 UITextField 的通过富文本方法修改属性。

#import "UISearchBar+ChangePrivateTextFieldSubview.h"

@implementation UISearchBar (ChangePrivateTextFieldSubview)

/// 修改SearchBar系统自带的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:关于如何查找自己的App项目是否使用了私有api,可以参考iOS查找私有API文章

2. 模态弹窗 ViewController 默认样式改变

模态弹窗属性 UIModalPresentationStyle 在 iOS 13 下默认被设置为 UIModalPresentationAutomatic新特性,展示样式更为炫酷,同时可用下拉手势关闭模态弹窗。

若原有模态弹出 ViewController 时都已指定模态弹窗属性,则可以无视该改动。

若想在 iOS 13 中继续保持原有默认模态弹窗效果。可以通过 runtime 的 Method Swizzling 方法交换来实现。

#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

3. 黑暗模式的适配

针对黑暗模式的推出,Apple官方推荐所有三方App尽快适配。目前并没有强制App进行黑暗模式适配。因此黑暗模式适配范围现在可采用以下三种策略:

  • 全局关闭黑暗模式
  • 指定页面关闭黑暗模式
  • 全局适配黑暗模式

3.1. 全局关闭黑暗模式

方案一:在项目 Info.plist 文件中,添加一条内容,Key为 User Interface Style,值类型设置为String并设置为 Light 即可。

方案二:代码强制关闭黑暗模式,将当前 window 设置为 Light 状态。

if(@available(iOS 13.0,*)){
self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
}

3.2 指定页面关闭黑暗模式

从Xcode 11、iOS 13开始,UIViewController与View新增属性 overrideUserInterfaceStyle,若设置View对象该属性为指定模式,则强制该对象以及子对象以指定模式展示,不会跟随系统模式改变。

  • 设置 ViewController 该属性, 将会影响视图控制器的视图以及子视图控制器都采用该模式
  • 设置 View 该属性, 将会影响视图及其所有子视图采用该模式
  • 设置 Window 该属性, 将会影响窗口中的所有内容都采用该样式,包括根视图控制器和在该窗口中显示内容的所有控制器

3.3 全局适配黑暗模式

配黑暗模式,主要从两方面入手:图片资源适配与颜色适配

图片资源适配

打开图片资源管理库 Assets.xcassets,选中需要适配的图片素材item,打开最右侧的 Inspectors 工具栏,找到 Appearances 选项,并设置为 Any,Dark模式,此时会在item下增加Dark Appearance,将黑暗模式下的素材拖入即可。关于黑暗模式图片资源的加载,与正常加载图片方法一致。

iOS13原生端适配攻略(推荐)

颜色适配

iOS 13开始UIColor变为动态颜色,在Light Mode与Dark Mode可以分别设置不同颜色。若UIColor色值管理,与图片资源一样存储于 Assets.xcassets 中,同样参照上述方法适配。若UIColor色值并没有存储于 Assets.xcassets 情况下,自定义动态UIColor时,在iOS 13下初始化方法增加了两个方法

+ (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);

这两个方法要求传一个block,block会返回一个 UITraitCollection 类

当系统在黑暗模式与正常模式切换时,会触发block回调

示例代码:

UIColor *dynamicColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull trainCollection) {
  if ([trainCollection userInterfaceStyle] == UIUserInterfaceStyleLight) {
   return [UIColor whiteColor];
  } else {
   return [UIColor blackColor];
  }
 }];

 [self.view setBackgroundColor:dynamicColor];

当然了,iOS 13系统也默认提供了一套基本的黑暗模式UIColor动态颜色,具体声明如下:

@property (class,nonatomic,readonly) UIColor *systemBrownColor  API_AVAILABLE(ios(13.0),tvos(13.0)) API_UNAVAILABLE(watchos);
@property (class,readonly) UIColor *systemIndigoColor  API_AVAILABLE(ios(13.0),readonly) UIColor *systemGray2Color  API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,watchos);
@property (class,readonly) UIColor *systemGray3Color  API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *systemGray4Color  API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *systemGray5Color  API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *systemGray6Color  API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *labelColor    API_AVAILABLE(ios(13.0),readonly) UIColor *secondaryLabelColor  API_AVAILABLE(ios(13.0),readonly) UIColor *tertiaryLabelColor  API_AVAILABLE(ios(13.0),readonly) UIColor *quaternaryLabelColor API_AVAILABLE(ios(13.0),readonly) UIColor *linkColor    API_AVAILABLE(ios(13.0),readonly) UIColor *placeholderTextColor API_AVAILABLE(ios(13.0),readonly) UIColor *separatorColor   API_AVAILABLE(ios(13.0),readonly) UIColor *opaqueSeparatorColor API_AVAILABLE(ios(13.0),readonly) UIColor *systemBackgroundColor     API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *secondarySystemBackgroundColor   API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *tertiarySystemBackgroundColor   API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *systemGroupedBackgroundColor   API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *secondarySystemGroupedBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *tertiarySystemGroupedBackgroundColor API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *systemFillColor       API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *secondarySystemFillColor    API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *tertiarySystemFillColor     API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,readonly) UIColor *quaternarySystemFillColor    API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(tvos,watchos);

监听模式的切换

当需要监听系统模式发生变化并作出响应时,需要用到 ViewController 以下函数

// 注意:参数为变化前的traitCollection,改函数需要重写
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection;

// 判断两个UITraitCollection对象是否不同
- (BOOL)hasDifferentColorAppearanceComparedToTraitCollection:(UITraitCollection *)traitCollection;

示例代码:

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
 [super traitCollectionDidChange:previousTraitCollection];
 // trait has Changed?
 if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
 // do something...
 }
 }

系统模式变更,自定义重绘视图

当系统模式变更时,系统会通知所有的 View以及 ViewController 需要更新样式,会触发以下方法执行(参考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;

4. LaunchImage即将废弃

使用 LaunchImage 设置启动图,需要提供各类屏幕尺寸的启动图适配,这种方式随着各类设备尺寸的增加,增加了额外不必要的工作量。为了解决 LaunchImage 带来的弊端,iOS 8引入了 LaunchScreen 技术,因为支持 AutoLayout + SizeClass,所以通过 LaunchScreen 就可以简单解决适配当下以及未来各种屏幕尺寸。

Apple官方已经发出公告,2020年4月开始,所有使用iOS 13 SDK 的App都必须提供 LaunchScreen。创建一个 LaunchScreen 也非常简单

(1)New Files创建一个 LaunchScreen,在创建的 ViewController 下 View 中新建一个 Image,并配置 Image 的图片
(2)调整 Image 的 frame 为占满屏幕,并修改 Image 的 Autoresizing 如下图,完成

iOS13原生端适配攻略(推荐)

5. 新增一直使用蓝牙的权限申请

在iOS13之前,无需权限提示窗即可直接使用蓝牙,但在iOS 13下,新增了使用蓝牙的权限申请。最近一段时间上传IPA包至App Store会收到以下提示。

iOS13原生端适配攻略(推荐)

解决方案:只需要在 Info.plist 里增加以下条目:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>这里输入使用蓝牙来做什么</string>`

6. Sign With Apple

在iOS 13系统中,Apple要求提供第三方登录的App也要支持「Sign With Apple」,具体实践参考 iOS Sign With Apple实践

7. 推送Device Token适配

在iOS 13之前,获取Device Token 是将系统返回的 NSData 类型数据通过 -(void)description; 方法直接转换成 NSString 字符串。

iOS 13之前获取结果:

iOS13原生端适配攻略(推荐)

iOS 13之后获取结果:

iOS13原生端适配攻略(推荐)

适配方案:目的是要将系统返回 NSData 类型数据转换成字符串,再传给推送服务方。-(void)description; 本身是用于为类调试提供相关的打印信息,严格来说,不应直接从该方法获取数据并应用于正式环境中。将 NSData 转换成 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;
}

8. UIKit 控件变化

主要还是参照了Apple官方的 UIKit 修改文档声明。iOS 13 Release Notes

8.1. UITableView

iOS 13下设置 cell.contentView.backgroundColor 会直接影响 cell 本身 selected 与 highlighted 效果。建议不要对 contentView.backgroundColor 修改,而对 cell 本身进行设置。

8.2. UITabbar

Badge 文字大小变化

iOS 13之后,Badge 字体默认由13号变为17号。建议在初始化 TabbarController 时,显示 Badge 的 ViewController 调用 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需设置 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将展示该动图效果)
UIImage *image = [UIImage imageWithCGImage:imageRef scale:image.size.width / CGRectGetWidth(imageView.frame) orientation:UIImageOrientationUp];

CGImageRelease(imageRef);

无文字时图片位置调整

iOS 13下不需要调整 imageInsets,图片会自动居中显示,因此只需要针对iOS 13之前的做适配即可。

if (IOS_VERSION < 13.0) {
  viewController.tabBarItem.imageInsets = UIEdgeInsetsMake(5,-5,0);
 }

8.3. 新增 Diffable DataSource

在 iOS 13下,对 UITableView 与 UICollectionView 新增了一套 Diffable DataSource API。为了更高效地更新数据源刷新列表,避免了原有粗暴的刷新方法 - (void)reloadData,以及手动调用控制列表刷新范围的api,很容易出现计算不准确造成 NSInternalInconsistencyException 而引发App crash。
api 官方链接

9. StatusBar新增样式

StatusBar 新增一种样式,默认的 default 由之前的黑色字体,变为根据系统模式自动选择展示 lightContent 或者 darkContent

针对iOS 13 SDK适配,后续将会持续收集并更新

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。