攻击UIButton,这是UIView的子视图

时间:2012-01-17 03:20:33

标签: ios cocoa-touch uiview uibutton selector

我无法捕捉UIButton的{​​{1}}的子视图。以下是我的代码设置方式:

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:确实是myButton的目标?

1 个答案:

答案 0 :(得分:1)

您可以通过记录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?