iOS11适配点击按钮崩溃

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pk_sir/article/details/78395628

iOS 11出来也个把月了,一直被其他事(Cross Fire)耽误了,没时间总结一下,今天就结合我们适配的经验来填一下坑。

问题一:项目换到iOS 11的环境下,点击页面按钮出现crash现象
1,在加班无数个夜晚后,终于知道原因了。一句话,就是不在主线程中修改了UI导致crash。
本来Xcode9 是可以提示这种错误的,

图一

但是有的比较隐晦的地方,它必须到运行时才能发现。而且不能定位到具体地方。在UINavigationBar的类别中,修改状态栏的颜色和一些通配属性,添加的方法没有放到主线程中(系统会这样认为的),当点击按钮时,push到下一个ViewController时,就会调用 UINavigationBar的类别然后crash。

//在UINavigationBar的类别中,修改状态栏的颜色和一些通配属性,添加的方法没有放到主线程中(系统会这样认为的)
if (!self.overlay) {
        [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        [self setShadowImage:[UIImage new]];
        self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, 20)];
        self.overlay.userInteractionEnabled = NO;
        self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self insertSubview:self.overlay atIndex:0];
    }
    self.overlay.backgroundColor = backgroundColor;
    [self setBackgroundColor:backgroundColor];

但是会有错误信息

=================================================================
Main Thread Checker: UI API called on a background thread: -[UIView init]
PID: 3735, TID: 1583390, Thread name: (none), Queue name: com.apple.root.default-qos, QoS: 21
Backtrace:
4   TestIOS11                           0x00000001032d25dd __29-[ViewController viewDidLoad]_block_invoke + 45
5   libdispatch.dylib                   0x0000000107bdd3f7 _dispatch_call_block_and_release + 12

解决办法:把修改UI的代码放回主线程。

    dispatch_async(dispatch_get_main_queue(), ^{
        // 把addSubview,insertSubview,放到这里
    });

猜你喜欢

转载自blog.csdn.net/pk_sir/article/details/78395628