bTagTiger
bTagTiger

Reputation: 1321

How can I send Button Event - UIControlEventTouchUpInside

In my simple program I have a problem with button. Button is a subView of a view and view is a subView of myViewController.view.

This Button is created dynamically but it's action doesn't work. How can I sent event?

Here's my code.

//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");
}

I can see my Button but I can't click. Have you got a idea please teach me.

Upvotes: 3

Views: 6545

Answers (1)

Your code should be like this:

 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];

Upvotes: 1

Related Questions