在“__strong id”类型的对象上找不到 UIAlertController 错误 'bounds'

UIAlertController error 'bounds' not found on object of type '__strong id'

我正在尝试创建一个提醒,当出现时会询问用户是否要 select 从他们的图库中获取照片或拍照。我正在使用 post UIPopover How do I make a popover with buttons like this? 中的模板。模板是...

UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                          message: nil
                                                                   preferredStyle: UIAlertControllerStyleActionSheet];
[alertController addAction: [UIAlertAction actionWithTitle: @"Take Photo" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    // Handle Take Photo here
}]];
[alertController addAction: [UIAlertAction actionWithTitle: @"Choose Existing Photo" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    // Handle Choose Existing Photo here
}]];

alertController.modalPresentationStyle = UIModalPresentationPopover;

UIPopoverPresentationController * popover = alertController.popoverPresentationController;
popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
popover.sourceView = sender;
popover.sourceRect = sender.bounds;

[self presentViewController: alertController animated: YES completion: nil];

但是 popover.sourceRect = sender.bounds; xcode 给我一个错误,指出 Property 'bounds' not found on object of type '__strong id'。这个错误是什么意思,如何解决?

您可能会接收 sender 作为此函数的参数,类型为 id,代表通用对象。编译器不知道它有一个名为 bounds 的 属性,因为它实际上可以是任何对象。要解决此问题,您需要通过强制转换告诉它 sender 实际上是 UIView *

UIView* senderView = (UIView *)sender; 

然后你可以进行下一个作业:

popover.sourceView = senderView;
popover.sourceRect = senderView.bounds;

问题出在您配置弹出窗口时。

在警报控制器开始显示之前,UIKit 框架不会创建 popoverPresentationController 属性。它直到下一个显示更新周期才会真正显示它,所以不用担心它会先闪烁未配置。

呈现警报控制器后进行配置,您应该没问题。