0

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
}
user9413194
  • 119
  • 2
  • 3
  • 9
  • how have you added nav bar items? – Sandeep Bhandari May 18 '20 at 04:46
  • @SandeepBhandari in viewDidLoad. ->. let continuousVisitsButton = Util.createRightButton("ic_skip_next") continuousVisitsButton.addTarget(self, action: #selector(continuousVisitsButtonPressed), for: UIControlEvents.touchUpInside) self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: continuousVisitsButton), Util.createSpaceItem(), UIBarButtonItem(customView: timeFilterButton)] – user9413194 May 18 '20 at 04:48
  • Did you check the solution provided? Did it work? – Sandeep Bhandari May 18 '20 at 08:47

2 Answers2

1

In viewDidLoad add a navigation bar button item like this:

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Go", style: .plain, target: self, action: #selector(yourFunctionToCall)) 

now write the function for the button action

@objc func yourFunctionToCall() {
    print("function called...")
}
Fabio
  • 5,432
  • 4
  • 22
  • 24
1
    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

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78