有些时候为了项目的需求需要(在一张广告的图片中,点击不同的区域,需要响应不同的操作)那么我们可以创建一个UIImageView,然后通过UIResponder的相关方法,获取当前的点击区域,通过判断分别处理事件。具体代码如下:
由于UIView继承UIResponder类,可以通过实现如下方法,来获取点击区域操作。
-(void)touchesBegan:(NSSet )touches withEvent:(nullable UIEvent )event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { [touches enumerateObjectsUsingBlock:^(UITouch * _Nonnull obj, BOOL * _Nonnull stop) { if (obj.view == self) { CGPoint touchPoint = [obj locationInView:self]; NSInteger index = [self locationJugement:touchPoint]; #ifdef DEBUG NSLog(@"touchPoint....:%@",NSStringFromCGPoint(touchPoint)); #endif if (self.delegate && [self.delegate respondsToSelector:@selector(tapEventOption:)]&& index >= 0) { [self.delegate tapEventOption:[self.hotSpotAdsArray safeObjectAtIndex:index]]; } *stop = YES; } }]; }
- (NSInteger)locationJugement:(CGPoint)point { __block NSInteger returnIndex = -1;//默认为-1 [self.hotSpotAdsArray enumerateObjectsUsingBlock:^(BBHotspotModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { #ifdef DEBUG NSLog(@"obj.rect...:%@",obj.rect); #endif if ([obj.rect count] >= 4) {//防止越界 CGFloat orgX = [[obj.rect objectAtIndex:0] floatValue]; CGFloat orgY = [[obj.rect objectAtIndex:1] floatValue]; CGFloat width = [[obj.rect objectAtIndex:2] floatValue]; CGFloat height = [[obj.rect objectAtIndex:3] floatValue]; if ( (point.x > orgX && point.x < orgX + width) && (point.y > orgY && point.y < orgY + height)) { returnIndex = idx; *stop = YES; } } }]; return returnIndex; } @end
|
可以通过以下方法测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| - (void)createTestModelArray { NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:4]; for (NSInteger j = 0; j < 4; j++) { NSArray *array = [[NSArray alloc] init]; BBHotspotModel *mode = [[BBHotspotModel alloc] init]; for (NSInteger i = 0; i < 4; i++) { NSInteger hang = ((j%2 == 0) ? j/2:(j/2)); NSInteger lei = ((j%2 == 0) ? 0:1); CGFloat orgX = lei * (SCREEN_WIDTH/2.0); CGFloat orgY = hang * (200/2.0); array = [NSArray arrayWithObjects:@(orgX),@(orgY),@(SCREEN_WIDTH/2.0),@(200/2.0),nil]; } mode.rect = array; mode.target = [NSString stringWithFormat:@"跳转%ld",j]; [tempArray addObject:mode]; } self.hotspotArray = [NSMutableArray arrayWithObjects:tempArray,nil]; }
|
经过测试发现,根据给定每一个特定区域,点击操作实现相关委托即可。