很簡單的一段代碼:
// 首先聲明一個UIAlertController對象 private var alertController: UIAlertController! // 初始化UIAlertController對象,中間省略彈出項 alertController = UIAlertController(title: self.selectDeviceModel?.name, message: nil, preferredStyle: .actionSheet) // 彈出alertController self.present(alertController, animated: true, completion: nil)
上面實現在屏幕底部彈出操作列表,在iPhone上面效果如下:
正常顯示,所有的列表項及操作都沒有問題。
可是就是這么一個簡單的功能,在iPad上測試時,直接程序崩潰,輸出了以下信息:
2018-08-07 09:25:41.064039+0800 InledcoLightSwift[2555:1299749] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0x146819600>) of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.'
*** First throw call stack:
(0x185902d8c 0x184abc5ec 0x190105dd4 0x18f95cd8c 0x18f95af60 0x18f8ba8b8 0x18f8b098c 0x18f795550 0x1858aa910 0x1858a8238 0x1858a8884 0x1857c8da8 0x1877ab020 0x18f7a978c 0x10278f27c 0x185259fc0)
libc++abi.dylib: terminating with uncaught exception of type NSException
崩潰信息原因是你的程序彈出了一個actionSheet類型的alterController.后面說是一個modal類型的,你就必須提供彈出的位置信息,可以是一個View或者一個barButtonItem,也就是說這個彈出框的來源,要從哪里彈出來。上面說到的UIModalPresentationPopover還不知道什么樣,只能試一試了。
那我們就按照提示信息設置一下看看都什么效果。
- 設置sourceView
alertController.popoverPresentationController?.sourceView = self.view;
效果如下
可以看到在屏幕左上角彈出了一個列表。
2.同時設置sourceRect
alertController.popoverPresentationController?.sourceView = self.view; alertController.popoverPresentationController?.sourceRect = CGRect(x: 10.0, y: 10.0, width: 100.0, height: 100.0);
效果如圖,在100, 100處彈出列表框
3.錯誤信息中還有一個barButtonItem,比如我設置self.navigationItem.rightBarButtonItem效果如下
綜上所述,在iPad上是沒有和iPhone上那種從底部彈出的效果的,我們只能設置sourceView或者barButtonItem來指定彈出的的位置。在iPad UIAlertController的類型為UIModalPresentationPopover,只能實現以上效果。