简体   繁体   中英

UIButton not getting touches when added to self.view

I have this scheme which is working fine ( --> = "has subview"):

ViewController.view --> imageView --> containerView --> UIButton

As expected, the button fires off the designated selector.
However, if I do the following (which for several reasons is preferable) the button stops receiving touches .

ViewController.view --> imageView
ViewController.view --> containerView --> UIButton
[self.view bringSubviewToFront:_containerView]; 

Any leads?

-- UPDATE

Responding to requests, here is some button creation code:

// in viewDidLoad

_controlsView = [[[NSBundle mainBundle] loadNibNamed:@"Controls" 
       owner:self options:nil] objectAtIndex:0];
_controlsView.frame = CGRectMake(0, 50, 
      _controlsView.bounds.size.width, _controlsView.bounds.size.height);
[self.view addSubview:_controlsView];
// ...
[_controlsView.superview bringSubviewToFront:_controlsView];

// in viewDidAppear

if (!_demoButton) {
   _demoButton = (UIButton*)[_controlsView viewWithTag:kDemoButtonTag];
   [_demoButton addTarget:self action:@selector(buttonPressed:) 
       forControlEvents:UIControlEventTouchUpInside];
   // configuration, color, font, layer, etc. all works well
}

Finally, the Controls.xib looks like this:

IB中的屏幕截图

Probably您的观点支配着您的按钮。

[self.view bringSubviewToFront:<UIButton_INSTANCE>];

Sometimes this happens, well has happened to me, when I have set a control element outside the frame of the container view. I've not tested this, but as you've got many nested views, it may occur on the first instance as the imageview may be large enough to encompass the UIButton.

Due to not enough codes, it is impossible to precisely figure out the reason why this happened.

I suppose you should try to write a category of UIButton to overwrite -touchesBegan:withEvent: -touchesMoved:withEvent: -touchesEnded:withEvent: with some debug info output like:

{
    [super touchesBegan:touches withEvent:event];
    NSLog(@"Touches began/moved/ended!");
}

When you pressed the UIButton instance, and the debug info was get printed, that means your UIButton's instance has received touch events but not handled it in right way. And in the opposite, that means there is an instance in respond chain blocked the events delivery.

Particularly, if it is found that only touches began debug info get printed and touches moved debug info no longer get printed after your fingers moved, your touch events probably were blocked by a gesture recognizer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM