【问题标题】:UIPopoverPresentationController can not be dismissed on iPhoneUIPopoverPresentationController 无法在 iPhone 上关闭
【发布时间】:2026-01-09 16:55:02
【问题描述】:

我正在实现一个 CABTMIDICentralViewController(Apple 的预制 BTLE MIDI 配置面板)。下面的代码是 Apple 的示例代码 - 未修改。

它在 iPad 上完美运行,但在 iPhone/iPod 上会导致无法关闭的全屏视图。代码清楚地创建了一个完成按钮,但它没有显示在设备上。

常见的答案是“你需要一个 UINavigationController”,但在这段代码中有一个。所以我不确定还缺少什么?

- (void)doneAction:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)configureCentral:(id)sender
{
    CABTMIDICentralViewController *viewController [CABTMIDICentralViewController new];

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];

    // this will present a view controller as a popover in iPad and modal VC on iPhone
    viewController.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                      target:self
                                                      action:@selector(doneAction:)];

    navController.modalPresentationStyle = UIModalPresentationPopover;

    UIPopoverPresentationController *popC = navController.popoverPresentationController;
    popC.permittedArrowDirections = UIPopoverArrowDirectionAny;
    popC.sourceRect = [sender frame];

    UIButton *button = (UIButton *)sender;
    popC.sourceView = button.superview;

    [self presentViewController:navController animated:YES completion:nil];
}

【问题讨论】:

    标签: objective-c iphone uipopovercontroller


    【解决方案1】:

    您必须实现 UIPopoverPresentationControllerDelegate 才能在 iPhone 中查看弹出框。默认情况下,它将以已经呈现的视图控制器的样式呈现。

    添加这段代码以将控制器显示为弹出框

    - (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller traitCollection:(nonnull UITraitCollection *)traitCollection {
        return UIModalPresentationNone;
    }
    

    【讨论】: