Reputation: 941
I have a UIBarButtonItem and i want to pushViewController in an other class. So i have this line of code in viewDidLoad :
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"settings"), style: .plain, target: self, action: #selector(GoToPages.goToSettings(_:)))
This is my GoToPages class :
import UIKit
class GoToPages: UIViewController {
@objc func goToSettings(_ sender:UIBarButtonItem) {
let button = sender
switch button.tag {
case 0:
let settingsPageView = self.storyboard?.instantiateViewController(withIdentifier: "Notifications")
self.navigationController?.pushViewController(settingsPageView!, animated: true)
case 1:
let settingsPageView = self.storyboard?.instantiateViewController(withIdentifier: "Settings")
self.navigationController?.pushViewController(settingsPageView!, animated: true)
default:
return
}
}
}
But i get an error : unrecognized selector sent to instance.
Upvotes: 0
Views: 1827
Reputation: 3899
You should delete 'GoToPages.' from selector definition of #selector(GoToPages.goToSettings(_:))
:
#selector(goToSettings(_:))
Because GoToPages.goToSettings is class function and should be instance method to work due to your argument 'target: self'. Here self specifies instance and therefore your selector must be instance method.
Just in case this doesn't solve your problem, use self.navigationItem.setRightBarButton(...)
instead of assigning directly to self.navigationItem.rightBarButtonItem = ...
Here is the code which works for me:
override func viewDidLoad() {
super.viewDidLoad()
let barButtonItem = UIBarButtonItem(image: UIImage(named: "image"),
style: .plain,
target: self,
action: #selector(barButtonItemTapped(sender:))
navigationItem.setRightBarButtonItems([barButtonItem], animated: true)
}
@objc private func barButtonItemTapped(sender: UIBarButtonItem) {
}
Upvotes: 1
Reputation: 941
My code :
import UIKit
extension UIViewController {
@objc func goToPage(_ sender: Any) {
guard let button = sender as? UIBarButtonItem else {
return
}
switch button.tag {
case 0:
let settingsPageView = self.storyboard?.instantiateViewController(withIdentifier: "Notifications")
self.navigationController?.pushViewController(settingsPageView!, animated: true)
case 1:
let settingsPageView = self.storyboard?.instantiateViewController(withIdentifier: "Settings")
self.navigationController?.pushViewController(settingsPageView!, animated: true)
default:
return
}
}
Upvotes: 0
Reputation: 285079
The value of the parameter target
must be the instance of the class the action
is implemented in.
self
implies that the action
is implemented in the current class.
Upvotes: 1