我在捕获作为UIButton子视图的UIView上的拍子时遇到问题。这是我的代码设置方式:

// 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


该按钮出现在视图中。当我点击按钮时,按钮的颜色会暂时改变。但是,选择器buttonTapped:永远不会被调用。知道为什么吗?

如何验证buttonTapped:确实是myButton的目标?

最佳答案

您可以通过记录r来验证您当前的班级是目标

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


但是,我将您的代码添加到了测试项目(单视图模板)中,并且buttonTapped:方法起作用了。

- (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;
}


问题出在别的地方。代码是否将MyClass的整个.h和.m发布?

09-05 17:51