如何在ScrollView滑动的瞬间禁用拖拽手势

简介:
+关注继续查看

如何在ScrollView滑动的瞬间禁用拖拽手势

效果:

在UIScrollView滑动的瞬间禁用pan手势,可以防止用户按着屏幕不放后导致出现的一些莫须有的bug.

//
//  ViewController.m
//  TableViewDemo
//
//  Created by XianMingYou on 15/2/23.
//  Copyright (c) 2015年 XianMingYou. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds
                                                  style:UITableViewStylePlain];
    self.tableView.delegate   = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"YouXianMing"];
 
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YouXianMing"];
    cell.textLabel.text   = @"YouXianMing";
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY <= -100) {
        // 存储这一瞬间的contentOffset值
        CGPoint storePoint = scrollView.contentOffset;
        
        // 禁止用pan手势(禁用pan手势瞬间会导致contenOffset值瞬间恢复成(0, 0))
        scrollView.panGestureRecognizer.enabled = NO;
        
        // 设置此时的contentOffset值
        scrollView.contentOffset = storePoint;
        
        [UIView animateWithDuration:0.5 animations:^{
            // 动画过渡
            scrollView.contentOffset = CGPointMake(0, 0);
        } completion:^(BOOL finished) {
            // 恢复手势
            scrollView.panGestureRecognizer.enabled = YES;
        }];
    }
}

@end

关键的一步:

(禁用手势后,需要存储当时的contentOffset值,然后再重设,用动画过渡即可)

目录
相关文章
swiper轮播-可支持触摸滑动(整理)
swiper轮播-可支持触摸滑动(整理)
swiper轮播-可支持触摸滑动(整理)
|
8月前
|
iOS开发
iOS开发 - ScrollView滚动时怎么判断滚动停止及滚动的方向
iOS开发 - ScrollView滚动时怎么判断滚动停止及滚动的方向
619 0
|
Android开发
RecycleView 不显示、显示不全及滑动卡顿
RecycleView 出现的不显示或显示不全。ScrollView中嵌套RecycleView滑动出现卡顿。
476 0
触屏事件-上下左右滑动
window.touchMove=function(){ // 用于纪录触摸开始时的坐标 var startX=0,startY=0, //创建一个变量,用于保存触摸方向 touchDirection=""; //创建一个对象,用于保存滑动事件 var funcs = {}; if(arguments.
1265 0
unity3d-ngui UIScrollView 滚动方向与滚轮相反
生成一个滚动面板之后发现滚轮向上滚,界面向下;滚轮向下界面向上。在编辑窗口里发现这个选项 本来是-2,修改成正数就可以了。   http://ju.outofmemory.cn/entry/146754
推荐文章
更多