iOS开发

iPad 弹框奔溃

2020-04-02  本文已影响0人  本帅不良

在使用系统弹框“UIAlertController”时,会莫名的崩溃。首先看下我们常规的写法:

UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [ac addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
    }]];
    [ac addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册选择
    }]];
    [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
在 iPhone 下的运行效果如图: A291D9BD84595670DFCE9BC8E6B6AF1D.png

但是 iPad 屏幕比较宽,如果还是底部全屏显示的话会不会很丑?所以苹果不让你这样显示,需要设置一些参数。
改进版:

UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [ac addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
    }]];
    [ac addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册选择
    }]];
    [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    if ([ac respondsToSelector:@selector(popoverPresentationController)]) {
        ac.popoverPresentationController.sourceView = cell; //必须加
        CGRect rect = cell.frame;
        ac.popoverPresentationController.sourceRect = CGRectMake(kScreenWidth-90, rect.origin.y-rect.size.height/2, rect.size.width, rect.size.height);//可选,我这里加这句代码是为了调整到合适的位置
    }
[self presentViewController:ac animated:YES completion:nil];

可以看到:我们只是加了一个 if 判断,并设置了 ac 的popoverPresentationController属性,我们可以看出这个属性是用来约束弹框显示的位置的。

iPad 下效果如图 D6C36C02AE95B38D2DF41ECE61D8F09F.png

注:这是弹框为“ UIAlertControllerStyleActionSheet”类型的显示情况,如果弹框为“UIAlertControllerStyleAlert”类型,由于都是居中显示,效果差异不大,故不需要这样设置。

上一篇 下一篇

猜你喜欢

热点阅读