UIBarButtonItem导致无法识别的选择器发送到实例

时间:2016-12-14 21:12:21

标签: ios swift

我想以编程方式在UIBarButtonItem上创建一个popovermenù,这是我编写的代码

    static func setNavigationRightButton(myView: UIViewController) {

    navBarBtn = UIButton(type: .custom)
    navBarBtn.addTarget(myView, action: #selector(pizza.handleFunc(_:)), for: .touchUpInside)
    navBarBtn.frame = CGRect(x: 0, y: 0, width: 33, height: 30)
    navBarBtn.imageView?.contentMode = .scaleAspectFit
    //navBarBtn.setTitle("10", for: .normal)
    setCartBadge()
    navBarBtn.titleLabel?.font = UIFont.systemFont(ofSize: 9)

    let barButton = UIBarButtonItem(customView: navBarBtn)
    myView.navigationItem.rightBarButtonItem = barButton
}

这是动作功能

    func handleFunc(_ sender: UIBarButtonItem!) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "ShoppingCartPopoverVC") as! ShoppingCartPopoverVC
    vc.preferredContentSize = CGSize(width: UIScreen.main.bounds.width, height: 100)
    let navController = UINavigationController(rootViewController: vc)
    navController.modalPresentationStyle = .popover
    let popOver = navController.popoverPresentationController
    popOver?.delegate = self
    popOver?.barButtonItem = sender
    self.present(navController, animated: true, completion: nil)
}

当我在这里“popOver?.barButtonItem = sender”应用程序因此错误而崩溃

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [UIButton _viewForPresenting]:无法识别的选择器发送到实例0x7faa0b5148f0'

1 个答案:

答案 0 :(得分:2)

您的目标/操作设置为UIButton,但您的操作方法为发件人指定了UIBarButtonItem而不是UIButton

您需要更新您的操作:

func handleFunc(_ sender: UIButton) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "ShoppingCartPopoverVC") as! ShoppingCartPopoverVC
    vc.preferredContentSize = CGSize(width: UIScreen.main.bounds.width, height: 100)
    let navController = UINavigationController(rootViewController: vc)
    navController.modalPresentationStyle = .popover
    let popOver = navController.popoverPresentationController
    popOver?.delegate = self
    popOver?.sourceView = sender
    popOver?.sourceRect = sender.bounds
    self.present(navController, animated: true, completion: nil)
}

请注意参数的更改以及弹出控制器上设置的属性。