开发者

Parent responds to child's touch

开发者 https://www.devze.com 2022-12-15 16:14 出处:网络
I have a UIScrollView with subclassed UIImageViews in it.When one of the imageviews are clicked, I\'d like the parent UIView (contains the scrollview) to receive the event in its

I have a UIScrollView with subclassed UIImageViews in it. When one of the imageviews are clicked, I'd like the parent UIView (contains the scrollview) to receive the event in its

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

I can tell if the imageview was clicked by

if(CGRectContainsPoint(myScrollView.frame, location) == YES){...}

Assuming the imageview and scrollview are the same size. Or is th开发者_JS百科ere a better way to to know a particular imageview within the scrollview was tapped? The imageviews are created dynamically.


The approach I've used for this in the past is to fire off a notification when a subview has been touched, with the subview as the object posted with the notification. You can then have your container view listen for the appropriate notification, and perform whatever action is needed based on the UIView instance that was selected.

You'd post the notification within the subview's -touchesEnded:withEvent: method as follows:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MySubviewWasTouched" object:self];

To set up listening for this notification, you'd place code like the following somewhere in the initialization of your view or view controller:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSubviewTouch:) name:@"MySubviewWasTouched" object:nil];

remembering to remove the observer in your teardown code for the the view or controller.

Finally, you'd need to implement the method that processes the receipt of the notification (-handleSubviewTouch: in the example above):

- (void)handleSubviewTouch:(NSNotification *)note;
{
    UIView *subviewThatWasTouched = [note object];

    // Your touch-handling logic here
}


Note that UIImageView ignores touches (or rather, lets them pass through to its superview) by default. Make sure you set your image views' userInteractionEnabled property to YES.


If the image views don't have any children, you can use the UIView method hitTest:withEvent:. It returns the farthest descendent of a UIView that contains a given touched point. So for example:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint location = [[touches anyObject] locationInView:myScrollView];
    UIView *touchedView = [myScrollView hitTest:location withEvent:event];
    // ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号