Search code examples
iosswiftuibuttonsubclassaddtarget

Swift: Target not getting called on a subclassed UIButton


CustomButton.swift

class CustomButton: UIButton {

    override func draw(_ rect: CGRect) {
        //drawing code
    }
}

ViewController.swift

let testCustom = CustomButton()
testCustom.draw(CGRect(x: 0, y: 0, width: 0, height: 0))
testCustom.isUserInteractionEnabled = true
testCustom.addTarget(self, action: #selector(Start(_:)), for: .touchUpInside)
self.view.addSubview(testCustom)

@objc func Start(_ sender: CustomButton) {
    print("pressed start")
}

The button appears on screen but the function does not get called upon pressing the button. Any ideas why?

I also tried the function and addTarget code within the CustomButton.swift but couldn't get that to trigger either.

Thanks for any help!


Solution

  • @MuhammadWaqasBhati made a good point asking about the frame.

    I was using addSublayer to draw the path I had created onto the screen. My mistake here was that I was setting values in the draw() function and adding the CAShapeLayer with addSublayer, but a frame for the button wasn't being set.

    Even though the layer that is drawn is a sublayer of the button, it appears at the coordinates and dimensions provided for the layer, without any relation to the frame of its "parent" button.

    The frame of the button could be (0, 0, 0, 0) or (0, 0, 100, 100) and the image drawn in addSublayer could still be at (250, 200, 75, 80) so that the visible image would be in one spot of the screen, but the actual button is in an unrelated spot to what is visible in its sublayer.