在外部点击时防止弹出窗口被关闭 (Swift)

Preventing Popover Dismissal When Tapping Outside (Swift)

我正在尝试防止用户在弹出窗口之外点击时关闭弹出窗口。我似乎对此有其他 questions/answers,他们似乎都建议使用 modalInPopover 作为视图。正如我所看到的那样,我已经在 viewDidAppear 中完成了这项工作。我有文本字段以及根据下拉菜单中的选择填充标签的按钮。在输入任何信息之前,它工作正常,并且在外面点击时不会关闭弹出窗口。当在文本字段中输入文本时,它也能正常工作。但是,一旦我在点击其中一个按钮后从下拉列表中进行选择,弹出窗口就会在触摸它的外部后消失。

关于为什么会这样,还有其他建议吗?是否与在文本字段上调用 ​​resignFirstResponder 有关?

您可以实施 UIPopoverControllerDelegate:

func popoverControllerShouldDismissPopover(popoverController: UIPopoverController) -> Bool {
    //return true when you need
    return false
}

这在 iOS 9.0 中已弃用,但如果您有一个支持 iOS 8 的项目,则必须使用它。

让我知道它是否适合你

在swift3,ios10

实施 UIPopoverPresentationControllerDelegate 后,以下函数似乎可以解决问题。

func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
    return false
}

如果有人仍在寻找解决方案,我希望这对您有所帮助。

更新: 使用 UIPopoverPresentationControllerDelegate

func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
        return false
    }

When displayed, taps outside of the popover window cause the popover to be dismissed automatically. To allow the user to interact with the specified views and not dismiss the popover, you can assign one or more views to the passthroughViews property. Taps inside the popover window do not automatically cause the popover to be dismissed. Your view and view controller code must handle actions and events inside the popover explicitly and call the dismiss(animated:) method as needed.

docs