简体   繁体   中英

iOS - Tap specific area in UIImageView and perform the action

I have an UIImageView of a floor plan and what the client wants to do is when he click a specific area in floor plan, it will display the interior image of that area... I don't have a problem displaying that area when clicked. My problem is the area to be clicked itself. Look at my initial implementation: (I don't know if it's the proper way)

在此处输入图片说明

Master Bath Area has an excess place where I put a Button in it, so when the user tap that area, I'll perform the action that display the interior image... Same also in "walk-in closet" area, I have 2 buttons.

So, Is there a way to optimize this implementation?

One option is use a UITapGestureRecognizer to imageView,then when the gesture is fired

- (IBAction)tap:(UITapGestureRecognizer*)sender {
    CGPoint touchPoint = [sender locationInView:yourimageview];  
   //Then decide the point in which area to do different action
}

You say

I don't have a problem displaying that area when clicked.

It would be important to know, how you display the area, as this could be the key to the solution of your problem.

If you have some path (CGPath, UIBezierPath) to determine what area to highlight, you could use the same paths for hit testing.Either in button subclasses, UIView subclasses or gesture recognizer.

ie This code uses the masking path of a layer, if present. Of course this could be several paths.

@implementation MyView
//
// ...
//
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGPoint p = [self convertPoint:point toView:[self superview]];
    if(self.layer.mask){
        if (CGPathContainsPoint([(CAShapeLayer *)self.layer.mask path], NULL, p, YES) )
            return YES;
    }else {
        if(CGRectContainsPoint(self.layer.frame, p))
            return YES;
    }
    return NO;
}

@end

A tap gesture recognizer will detect a tap on the view only if it is inside this path.

The same pointInside:withEvent: would work for an UIButton subclass based on paths.

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