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不同引起的。当然也和设备类型有关系,是一个比较容易忽略的地方。
网友评论