-->

iPhone - UIbutton nested in UIView does not respon

2020-07-10 10:51发布

问题:

I have a UIView (view B) with a UIButton on it.

I add this view B to my main view (view A) in an area outside of the bounds of the main view and I than animate it in with a UIView animation.

After the UIView animation is complete and View B is now on top of View A so the button is visible, the button does not respond to touches... I have never seen this before but this is the first app I am doing with the new iOS (iOS 5). Any ideas?

Thanks in advance.

回答1:

Is this the situation you are describing? Because it seems to work fine. Did you check if userInteractionEnabled is set to YES on the UIView?

- (void)buttonPressed:(UIButton*)button
{
    NSLog(@"button pressed");
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, -100, 100, 100)];
    view.backgroundColor = [UIColor blackColor];

    UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Button" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 10, 100, 20);
    [view addSubview:button];

    [self.view addSubview:view];

    [UIView animateWithDuration:0.5 animations:^{
        view.transform = CGAffineTransformMakeTranslation(0, 100);
    }];

    [view release];
}


回答2:

I'm not sure that this was answered so I give it a shot, just for the record:

Check that the buttons are not outside the frame of any superview.

I found that a button placed outside like this may not work. Come to think about it, this is weird. I ran into this when I was making a view with buttons that animates in from below. Underneath this I have a gray touchable view to allow cancel. Only problem was that 1) for the gray area I used the parent view itself and 2) I let this gray area shrink as the subview animated in place ... so as a result, the buttons became outside, and it didn't work.

Solution was to leave the view full size and either add another as the gray, or make the first one gray and not shrunk (the only reason I wanted to avoid this was that it would make a pile of half transparent layers which is not optimal). Then the view with buttons on top of that. :)

Hope this helps.



回答3:

If you have created the Button through programming then you have to do :-

myButton.userInteractionEnabled =YES;

Hope it Helps... :)