I have a button in my view class attempting to add a selector function from a separate class as follows:
class ProfileView: UIView {
createAccountButton.addTarget(self, action: #selector(ProfileViewController.createAccountClicked), for: .touchUpInside)
}
class ProfileViewController: UIViewController {
func createAccountClicked() {
print("button press")
}
}
I am getting a unrecognized selector error when I am trying to reference this method outside of ProfileView
. However it works when I simply put createAccountClicked()
into ProfileView
and call:
createAccountButton.addTarget(self, action: #selector(self.createAccountClicked), for: .touchUpInside)
instead. My question is - Is it possible to call a function from a separate class? Or would just having the function in the same class be the correct design pattern to follow?
For your issue try changing the code like below:
class ProfileView: UIView {
createAccountButton.addTarget(ProfileViewController, action: #selector(ProfileViewController.createAccountClicked), for: .touchUpInside)
}
Is it possible to call a function from a separate class? Or would just having the function in the same class be the correct design pattern to follow?
Yes, you can call a function from outside by declaring a class function or an object of that class. Check the class function below
class ProfileViewController: UIViewController {
class func someTypeMethod() {
//body
}
}