1

I'm having trouble capturing taps on a UIButton that's a subview of a UIView. Here's how my code is setup:

// in MyClass.m
@interface MyClass ()
@property (nonatomic, retain) UIButton *myButton;
@end

@implementation MyClass
@synthesize myButton;

- (void) buttonTapped:(id) sender {
    NSLog(@"button tapped!");
}

- (id) initWithFrame:(CGRect)frame {
    if (!(self = [super initWithFrame:CGRectZero]))
        return nil;

    myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [myButton setImage:[UIImage imageNamed:@"image.png"] 
                                  forState:UIControlStateNormal];
    [myButton addTarget:self 
                 action:@selector(buttonTapped:)
       forControlEvents:UIControlEventTouchUpInside];
    myButton.exclusiveTouch = YES;
    myButton.frame = CGRectMake(100, 100, 100, 100);
    [self addSubview:myButton];

    return self;
}

- (void) dealloc {
    [myButton release];
    [super dealloc];
}

@end

The button appears in the view. The button color changes momentarily when I tap it. However the selector buttonTapped: is never called. Any idea why?

How can I verify that buttonTapped: is indeed a target of myButton?

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

1 Answers1

1

You could verify that your current class is a target by logging the r

NSLog(@"actions for target %@",[myButton actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]);

However, I added your code to a test project (single view template) and the buttonTapped: method worked.

- (void) buttonTapped:(id) sender {
  NSLog(@"button tapped!");
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{


    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
  UIButton * myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [myButton setImage:[UIImage imageNamed:@"image.png"] 
            forState:UIControlStateNormal];
  [myButton addTarget:self 
               action:@selector(buttonTapped:)
     forControlEvents:UIControlEventTouchUpInside];
  myButton.exclusiveTouch = YES;
  myButton.frame = CGRectMake(100, 100, 100, 100);
    [rv.view addSubview:myButton];

    return YES;
}

The issue is somewhere else. Is the code posted the whole .h and .m for MyClass?

Jesse Black
  • 7,966
  • 3
  • 34
  • 45
  • Found the solution here: http://stackoverflow.com/questions/3344341/uibutton-inside-a-view-that-has-a-uitapgesturerecognizer. It's related to using UIGestureRecognizers. – SundayMonday Jan 17 '12 at 03:53