Reputation: 119
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
}
Upvotes: 0
Views: 654
Reputation: 20369
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
Upvotes: 1
Reputation: 5628
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...")
}
Upvotes: 2