UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
for (int i = 0; i < 10; i++) {
UIAlertAction *action = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"actionTitle%d",i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alertController addAction:action];
}
alertController.popoverPresentationController.sourceView = self.view;
alertController.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
[self presentViewController:alertController animated:YES completion:nil];
當在iPad上運行上面這段代碼的時候翎卓,如果沒有設置如下兩個屬性 alertController.popoverPresentationController.sourceView
alertController.popoverPresentationController.sourceRect
會導致程序crash。然而在iPhone上沒有這樣的問題。
錯誤提示內容如下:
Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0x14f735790>) 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
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
message:@"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
然而上面的這段代碼摘自官方文檔,比較之后是因為preferredStyle不同引起的囤采。當然也和設備類型有關系,是一個比較容易忽略的地方剪决。