Xcode开发下iPad端相机与照片库选择弹窗报错的适配问题
问题根因
iPad设备下,UIAlertController的.actionSheet样式默认采用UIModalPresentationPopover弹出样式,必须指定popover的锚点位置(sourceView、sourceRect或barButtonItem),未配置就会触发运行时崩溃。
你之前尝试把iPad端的弹窗样式改成.alert虽然能避免弹窗崩溃,但不符合Apple设计规范,也会导致相册选择器在iPad端弹出时触发同类崩溃,不需要修改原有弹窗样式,仅需补充popover锚点配置即可完成全设备适配。
完整适配代码
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBAction func TapOnImageView(sender: UITapGestureRecognizer) { // 传入触发点击的视图作为弹窗统一锚点 self.showAlert(anchorView: sender.view ?? self.view) } //Show alert to selected the media source type. private func showAlert(anchorView: UIView) { let alert = UIAlertController(title: "Image Selection", message: "From where you want to pick this image?", preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in self.getImage(fromSourceType: .camera, anchorView: anchorView) })) alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in self.getImage(fromSourceType: .photoLibrary, anchorView: anchorView) })) alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil)) // 适配iPad端actionSheet的popover锚点,iPhone端该属性为nil无额外影响 if let popover = alert.popoverPresentationController { popover.sourceView = anchorView popover.sourceRect = anchorView.bounds } self.present(alert, animated: true, completion: nil) } //get image from source type private func getImage(fromSourceType sourceType: UIImagePickerController.SourceType, anchorView: UIView) { //Check is source type available if UIImagePickerController.isSourceTypeAvailable(sourceType) { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = sourceType // 适配iPad端相册选择器的popover锚点,避免选相册时崩溃 if sourceType == .photoLibrary, let popover = imagePickerController.popoverPresentationController { popover.sourceView = anchorView popover.sourceRect = anchorView.bounds } self.present(imagePickerController, animated: true, completion: nil) } } //MARK:- UIImagePickerViewDelegate. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { self.dismiss(animated: true) { [weak self] in guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } //Setting image to your image view self?.imageView.image = image self?.imageView.contentMode = .scaleToFill self?.image = self?.imageView.image } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
适配说明
- 所有适配逻辑自动兼容iPhone、iPad双端:iPhone设备下
popoverPresentationController属性为nil,适配代码不会执行,完全保留原有iPhone端交互逻辑 - 弹窗、相册选择器均从用户点击的图片视图位置弹出,符合Apple交互设计规范
- 无需修改原有弹窗样式,iPhone端保持底部弹出操作表的体验,iPad端自动从触发位置弹出popover窗口
- 你之前尝试修改弹窗为.alert的方案虽能解决弹窗崩溃,但未覆盖相册选择器的iPad适配,仍会在选相册时触发崩溃
内容的提问来源于stack exchange,提问作者Pressing_Keys_24_7
相关产品推荐
相关产品推荐

