在使用系统弹框“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 下的运行效果如图:

但是 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属性,我们可以看出这个属性是用来约束弹框显示的位置的。

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