在我的简单程序中,我遇到按钮问题。 Button是视图的子视图,视图是myViewController.view的子视图。
此按钮是动态创建的,但它的动作不起作用。我怎样才能发送活动?
这是我的代码。
//的ViewController
- (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");
}
我可以看到我的按钮,但我无法点击。你有什么想法请教我。
答案 0 :(得分:1)
您的代码应该是这样的:
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];