适配iOS11, Xcode 9遇到的问题

303 阅读2分钟

1: 计算 UITableView 的 contentSize

今天在 Xcode 9 GM 上,调试项目中的活动列表时,发现 UITableView 计算的高度不正确.在 Xcode 8.3 上调试, contentSize 没有问题.

Xcode 8.3 上打印 tableview 的 contentSize, 如下:

po self.tableView.contentSize

(width = 300, height = 938)

Xcode 9 GM 上打印 tableview 的 contentSize, 如下:

po self.tableView.contentSize

(width = 300, height = 661)

苹果开发者论坛给出的解释:在 iOS 11 中,默认使用估算的高度,也就意味着 contentSize 是一个估算的高度,并非准确的高度.如果你不想用估算的高度,需要设置三个属性,如下:

self.tableView.estimatedRowHeight = 0;

self.tableView.estimatedSectionHeaderHeight = 0;

self.tableView.estimatedSectionFooterHeight = 0;

2:导航控制器(UINavigationController)中的"返回"(BackButton)按钮坐标下沉

在 iOS 11以前的版本,大家通过以下的方法,隐藏"返回"按钮中的字体内容.

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-60, -60) forBarMetrics:UIBarMetricsDefault];

然后,在 iOS 11中调试,发现"返回"按钮的坐标下沉了.如下两幅对比图: iOS 11以前的版本:

normal.png
iOS 11的版本:
abnormal.png

解决方法:(2017-11-12修改,增加新的解决方案,废弃以前的解决方案)

if(@available(iOS 11, *)) {
    //2017-11-12 新增 (手势侧滑返回速度很慢时,能够看到"偏移出屏幕的标题")
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-200, 0) forBarMetrics:UIBarMetricsDefault];

    //这种解决方案(下面的两行代码),会影响全局的 BarButtonItem 的 title text color, 比如: leftBarButtonItem, rightBarButtonItem,不推荐使用
    //[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
    //[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];
} else {
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-60, -60) forBarMetrics:UIBarMetricsDefault];
}

或者统一处理,不区分版本:

//2017-11-12 废弃下面的解决方案
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];

3:用Xcode 9向工程中添加资源的问题:

①:如果向工程中拖入其他代码文件(例如: firstView.h, firstView.m),然后再次编辑 .m 文件的时候,发现代码全是白色,并且没有代码提示功能.其他文件引用还会报错! 解决方案:

TARGETS => Build Phases => Compile Sources 将新添加的 .m 文件加入即可.

②:如果向工程中拖入其他资源文件(例如:happy.mp3, moreData.plist),加载资源的时候,返回的结果为 nil.

#列子:
po [[NSBundle bundleForClass:[self class]] URLForResource:@"happy.mp3" withExtension:nil];
nil

解决方案:

TARGETS => Build Phases => Copy Bundle Resources 将新添加的 .mp3 文件加入即可.

此篇博客用于搜集适配 iOS 11, Xcode 9遇到的问题,欢迎补充和纠错.(待续)