最近在写百度地图的时候发现地图和scrollView和tableView的滑动手势会冲突,这里以百度地图作为示例写一遍解决方法
首先遵循UIGestureRecognizerDelegate代理方法
然后在你需要禁止滑动的scrollView添加手势
// 给第一个tableView添加手势
UIGestureRecognizer *mainScrollVTap = [[UIGestureRecognizer alloc]init];
mainScrollVTap.delegate=self;
[scroAll addGestureRecognizer:mainScrollVTap];
// 给最底部的scrollview 添加手势
UIGestureRecognizer *mainScrollVTap = [[UIGestureRecognizer alloc]init];
mainScrollVTap.delegate=self;
[scroAll addGestureRecognizer:mainScrollVTap];
在地图上添加点击手势
_mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, PTTotalHeight/5*2)];
_mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
_mapView.delegate = self;
_mapView.showsUserLocation = YES;//显示定位图层
[scroRoute addSubview:_mapView];
//给地图加手势以解决滑动冲突
UITapGestureRecognizer *provinceMapTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(provinceMapTapped)];
provinceMapTap.delegate = self;
[_mapView addGestureRecognizer:provinceMapTap];
最后实现手势代理方法判断出需要触发哪一个手势
#pragma mark 手势代理方法 ,判断触摸的是地图还是外层的view
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
//判断如果是百度地图的view 既可以实现手势拖动 scrollview 的滚动关闭
if ([gestureRecognizer.view isKindOfClass:[BMKMapView class]] ){
scroAll.scrollEnabled = NO;
scroRoute.scrollEnabled = NO;
return YES;
}else{
scroAll.scrollEnabled = YES;
scroRoute.scrollEnabled = YES;
return NO;
}
}
需要注意的一点是给地图添加了点击手势需要实现方法,不然会崩溃
-(void)provinceMapTapped{
}
演示效果
示例.gif顺便整理一下如何判断scrollView的滑动方向
声明变量
@interface ViewController ()<UIScrollViewDelegate>
{
UIScrollView *scro;
float lastContentOffsetX;
float lastContentOffsetY;
}
在scrollViewWillBeginDragging方法里记录开始前的X、Y值
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
lastContentOffsetY = scrollView.contentOffset.y;
lastContentOffsetX = scrollView.contentOffset.x;
}
在scrollViewDidScroll方法里判断滑动方向
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
if(scrollView.contentOffset.y>lastContentOffsetY){
NSLog(@"向上滑动");
}else if(scrollView.contentOffset.y<lastContentOffsetY){
NSLog(@"向下滑动");
}
if(scrollView.contentOffset.x<lastContentOffsetX){
NSLog(@"向左滑动");
}else if(scrollView.contentOffset.x>lastContentOffsetX){
NSLog(@"向右滑动");
}
}
网友评论