kinkee
kinkee

Reputation: 368

Programmatically created custom view with button target

I'm having an custom UIView subclass which has some UIButtons appended. For every button there is an target action defined on the UIViewController which is including the custom UIView.

Somehow the TouchUpInside event is never being caught within the custom view including ViewController. Since UIViews are part of the UIResponderChain I wonder why events are not being fired? Does it make any sense to delegate the target action or should this be done another way?

Custom UIView Subclass: CustomView

let button = UIButton(frame: CGRectMake(10.0, 10.0, 100.0, 100.0))
button.addTarget(self.delegate, action: "buttonTapped:", forControlEvents: .TouchUpInside) 

ViewController

// Include the custom view
let customView = CustomView()
customView.delegate = self
self.view.addSubview(customView)
...

func buttonTapped(sender: AnyObject!) {
    // Doesn't get called
}

Upvotes: 2

Views: 2098

Answers (3)

Duncan C
Duncan C

Reputation: 131501

Do you set userInteractionEnabled to YES on your custom view? It's NO by default on views that are not descended from UIResponder (mostly buttons).

If a view's userInteractionEnabled = NO, it will ignore touch events.

Upvotes: 1

kinkee
kinkee

Reputation: 368

Unfortunately I was missing to declare the frame rect for the buttons - so buttons are being displayed, but they're indeed not clickable.

Upvotes: 0

Vitalii Gozhenko
Vitalii Gozhenko

Reputation: 9344

I assume self.delegate is nil when you adding target... Few solutions:

  • initialise custom view with delegate (create custom function initWithFrame:delegate)
  • override setDelegate function for custom view, and add target to button there;
  • make button variable public, and manually add target to it in your external class

Upvotes: 0

Related Questions