在 iPhone 的导航栏中显示来自栏按钮的弹出窗口

Showing pop over from Bar Button in Navigation bar in iPhone

在 Swift 中,我试图从导航栏右上角的栏按钮项显示弹出窗口。下面是我的代码:

func showOptions(sender: UIBarButtonItem) {
    let optionsVC = OptionsViewController(nibName: "OptionsViewController", bundle: nil)
    optionsVC.delegate = self
    optionsVC.modalPresentationStyle = .popover
    optionsVC.preferredContentSize = CGSize(width: 200, height: 200)

    present(optionsVC, animated: true, completion: nil)

    let popController = optionsVC.popoverPresentationController
    popController?.permittedArrowDirections = .up
    popController?.delegate = self
    popController?.barButtonItem = sender
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    return .none
}

它在 iPad 中运行良好,但在 iPhone 中运行良好。我浏览了文档和不同的网页。一切似乎都是对的。我的代码中缺少什么?

这里唯一的问题是您在设置弹出窗口委托之前呈现 OptionsViewController。所以首先设置它的委托然后调用当前函数。

let popController = optionsVC.popoverPresentationController
popController?.permittedArrowDirections = .up
popController?.delegate = self
popController?.barButtonItem = sender

present(optionsVC, animated: true, completion: nil)