PopoverPresentationController 为 nil

PopoverPresentationController coming as nil

创建了一个 SingleViewApplication,其中我放置了一个按钮。

现在单击按钮,我需要将 tableView 显示为弹出窗口。 TableViewController 是在 xib 中创建的。

问题是 tableViewController.popoverPresentationController 总是出现 nil 见下面的代码

     let filterVC =  TableViewController(nibName: "TableViewController", bundle: nil)
    var filterDistanceViewController = UINavigationController(rootViewController: filterVC)
    filterDistanceViewController.preferredContentSize = CGSize(width: 300, height: 200)
    let popoverPresentationViewController = filterDistanceViewController.popoverPresentationController
    popoverPresentationViewController?.permittedArrowDirections = .any


    if let pop = filterDistanceViewController.popoverPresentationController {
        pop.delegate = self
    }

在上面的代码中 filterDistanceViewController.popoverPresentationController 总是以 nil

出现

任何正确方向的提示将不胜感激。

您没有展示任何东西,所以您需要在当前viewcontroller上展示popoverPresentationViewController,例如:

@IBAction func importantButtonPressed(_ sender: UIButton) {
         let tableViewController = UITableViewController()
         tableViewController.modalPresentationStyle = .popover

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

        if let pop = tableViewController.popoverPresentationController {
          pop.delegate = self
        }

    }

你可以按照下面的方式做。

@IBAction func popoverBtnPressed(_ sender: Any) {

    let vc2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController2")
    vc2.modalPresentationStyle = .popover
    vc2.popoverPresentationController?.delegate = self
    vc2.popoverPresentationController?.barButtonItem = popoverBtn
    vc2.popoverPresentationController?.sourceRect = .zero
    present(vc2, animated: true, completion: nil)
}

在 VC 上设置 modalPresentationStyle 之前,popoverPresentationController 属性 将是 nil。确保在访问之前设置 modalPresentationStyle