简体   繁体   中英

Tapping UIButton that's a subview of UIView

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM