2
votes

I want to create a popover menù on an UIBarButtonItem programmatically, this is the code i write

    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
}

and this is the action func

    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)
}

when i'm here "popOver?.barButtonItem = sender" the app crash with this error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton _viewForPresenting]: unrecognized selector sent to instance 0x7faa0b5148f0'

1
You have UIButton here navBarBtn = UIButton(type: .custom) and func handleFunc(_ sender: UIBarButtonItem!) expecting UIBarButtonItem.Jay
that has nothing to do with the crash.tGilani

1 Answers

3
votes

Your target/action is being set to a UIButton but your action method specifies a UIBarButtonItem instead of a UIButton for the sender.

You need to update your action:

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)
}

Note the change to parameter and the properties set on the popover controller.