Reputation: 1255
I am facing this problem: I would like to assign an action for a button created runtime, I'm using this custom class:
import UIKit
class SubViewManager: NSObject {
var button = UIButton()
Then I have the function to add the button in the view:
frame.addSubview(button)
And the function for assign the action:
func setButtonAction(sender: UIButton!, buttonAction: Selector) {
button.addTarget(self, action: buttonAction, forControlEvents: UIControlEvents.TouchUpInside)
}
Now in the ViewController Class I call the SubViewManager object like this:
var newSubView:SubViewManager!
Then in a procedure I'm doing:
newSubView.addButton(...//Dimension and details//...)
newSubView.setButtonAction(newSubView.button, buttonAction: "save")
And here I have the problem, this error appair in the console:
unrecognized selector sent to instance 0x7f92f9694140
What I am doing wrong?
EDIT: I noticed that if I initialize the object directly in the function where I call the .setButtonAction
it works, but I can't declare in the same function because I need it in multiple functions!
RE-EDIT: When i do the .addTarget
method I would like to run a ViewController Class's procedure but it runs the SubViewManager procedure which don't exist, that's the why of the error, but I don't know how to run the ViewController Class procedure while calling the .addTarget
in an external class.
Upvotes: 0
Views: 1413
Reputation: 246
its crashing because in your code the target that you set to handle the button's action event is the SubViewManager instance ('self' inside setButtonAction method)
func setButtonAction(sender: UIButton!, buttonAction: Selector) {
button.addTarget(self, action: buttonAction, forControlEvents: UIControlEvents.TouchUpInside)
}
But the actually object where you implemented the save function is ViewController class.
You can try modify the parameter of the setButtonAction method to pass the target that will implemented the button action instead of unused sender : UIButton!
because you already call addButton method and has button property to point to it already.
Try something like this
func setButtonAction(target: AnyObject! , buttonAction: Selector) {
button.addTarget(target, action: buttonAction, forControlEvents: UIControlEvents.TouchUpInside)
}
Then pass in the viewController when you calling the setButtonAction method
newSubView.setButtonAction(self, buttonAction: "save")
where self
is instance of the ViewController class that implemented the save function.
Upvotes: 3