Search code examples
swiftuinavigationbaruibarbuttonitem

Why UIBarButtonItem target and action comes nil?


I Want to press UIBarButtonItem programmatically in swift. I looked at the other questions asked in stackoverflow and did the same, but it didn't work.doing what i want when manually clicked but I need click programmatically. My example code is

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let items =  self.navigationItem.rightBarButtonItems
    let item = items?.first


    UIApplication.shared.sendAction(item.action, to: item?.target, from: nil, for: nil) // not working


    _ = item.target?.perform(item.action, with: nil) // not working

    let action = item.action // result is  nil
    let target = item.target  / result is nil and item is not nil
}

Solution

  •     let items =  self.navigationItem.rightBarButtonItems
        let item = items?.first
        (item.customView as? UIButton).sendActions(for: .touchUpInside)
    

    self.navigationItem.rightBarButtonItems.first will return UIBarButtonItem not your continuousVisitsButton button and you had set your target and selector to your continuousVisitsButton not to your UIBarButtonItem

    In fact you simply created a UIBarButtonItem with customView and set it as right bar button item.

    self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: continuousVisitsButton)
    

    Clearly your rightBarButton item neither has target nor action hence printing returns nil.

    What you need is customView inside it which has both these properties configured, So rather than trying to send touch event to bar button item access its custom view and send touch event to it, to actually trigger selector :)

    . Hope this helps