Reputation: 6119
I'm trying to build a custom controller to manage a set of UIButtons.
ViewController where buttons are setup and placed:
override func viewDidLoad() {
super.viewDidLoad()
let button1 = UIButton()
button1.setTitle("Button 1", for: UIControlState.normal)
button1.setTitleColor(UIColor.blue, for: UIControlState.normal)
button1.frame.origin.y = 120
button1.sizeToFit()
button1.isUserInteractionEnabled = true
let button2 = UIButton()
button2.setTitle("Button 2", for: UIControlState.normal)
button2.setTitleColor(UIColor.blue, for: UIControlState.normal)
button2.frame.origin.y = 160
button2.sizeToFit()
let button3 = UIButton()
button3.setTitle("Button 3", for: UIControlState.normal)
button3.setTitleColor(UIColor.blue, for: UIControlState.normal)
button3.frame.origin.y = 190
button3.sizeToFit()
let controller = CustomButtonController(buttons: button1, button2, button3)
self.view.addSubview(button1)
self.view.addSubview(button2)
self.view.addSubview(button3) }
CustomButtonController:
class CustomButtonController : NSObject {
init(buttons: UIButton...) {
super.init()
for aButton in buttons {
aButton.addTarget(self, action: #selector(pressed(_:)), for: UIControlEvents.touchUpInside)
}
}
func pressed(_ sender: UIButton) {
print("Press received in CustomButtonController")
//Never gets called
}
}
If I use addTarget method on a button from inside the ViewController, then it works fine. Any idea why we can't add target to a passed UIButton like that? Thanks
Upvotes: 0
Views: 442
Reputation: 114836
You are creating your CustomButtonController
as a local constant in viewDidLoad
. As soon as viewDidLoad
returns, this object is released and so is no longer around to handle the button taps.
You need to declare an instance property to hold the controller instance:
var controller: CustomButtonController!
override func viewDidLoad() {
super.viewDidLoad()
let button1 = UIButton()
button1.setTitle("Button 1", for: UIControlState.normal)
button1.setTitleColor(UIColor.blue, for: UIControlState.normal)
button1.frame.origin.y = 120
button1.sizeToFit()
button1.isUserInteractionEnabled = true
let button2 = UIButton()
button2.setTitle("Button 2", for: UIControlState.normal)
button2.setTitleColor(UIColor.blue, for: UIControlState.normal)
button2.frame.origin.y = 160
button2.sizeToFit()
let button3 = UIButton()
button3.setTitle("Button 3", for: UIControlState.normal)
button3.setTitleColor(UIColor.blue, for: UIControlState.normal)
button3.frame.origin.y = 190
button3.sizeToFit()
controller = CustomButtonController(buttons: button1, button2, button3)
self.view.addSubview(button1)
self.view.addSubview(button2)
self.view.addSubview(button3)
}
Upvotes: 2