UIView: Let subviews receive touches, but not main

2019-04-06 03:56发布

问题:

I've got several cells containing views in this structure:

  • Main view
  • backview
  • frontview

The cells partly overlap. This means that the main view of cell A will partly cover the frontview of cell B. Like this:

  • B main view
  • B backview
  • B frontview
    • A main view
    • A backview
    • A frontview

I want to intercept touches on frontviews and backviews, but I want main views to ignore them.

(I've tried disabling user interaction on main views, but that also disables front and back views).

Any tips?

回答1:

I found an answer here: http://vectorvector.tumblr.com/post/2130331861/ignore-touches-to-uiview-subclass-but-not-to-its

Basically, I'm making the main view a subclass of UIView, and overriding hitTest with this:

-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    id hitView = [super hitTest:point withEvent:event];
    if (hitView == self) return nil;
    else return hitView;
}

(Note that confusingly you must set UserInteractionEnabled to true, ticked, yes for the UIView in question!)



标签: ios uiview touch