如何发送按钮事件 - UIControlEventTouchUpInside

问题描述:

在我的简单程序中,我遇到了按钮问题。 Button是视图的子视图,视图是myViewController.view的子视图。如何发送按钮事件 - UIControlEventTouchUpInside

此按钮是动态创建的,但它的操作不起作用。我怎样才能发送活动?

这是我的代码。

//视图控制器

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 

    bookCount = 0; 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)]; 
     [self.view addSubview:subview]; 
     UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [btn setFrame: subview.bounds]; 
     [btn addTarget:self action:@selector(onBtnchild:) forControlEvents:UIControlEventTouchUpInside]; 
     [subview addSubview:btn]; 
     ..... 
    } 
    return self; 

} 
-(void) onBtnchild:(id) sender{ 
    NSLog(@"HI"); 
} 

我可以看到我的按钮,但我不能点击。你有没有想法请教我。

您的代码应该是这样的:

UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)]; 

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

[btn setFrame: subview.bounds]; 

[btn addTarget:self action:@selector(onBtnchild:) 
     forControlEvents:UIControlEventTouchUpInside]; 

[subview addSubview:btn]; 

[self.view addSubview:subview]; 
+0

我一直流到你的代码。但我找不到差异。怎么了? – bTagTiger

+0

只需复制粘贴并回复 –

+0

谢谢。它工作正常。但我还有其他问题。当我添加imageView超级按钮。它不起作用。 – bTagTiger