UIScrollView底层实现

作者: geekAppke | 来源:发表于2018-05-07 21:51 被阅读11次
    scrollView之所以能滚动是因为改了bounds
    手指往上拖,bounds++,内容往上走
    bounds 对外面的对象没有影响,但对里面的子控件有影响
    

    普通View实现UIScrollView功能

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIView *scrollView = [[UIView alloc] init];
        scrollView.frame = self.view.bounds;
        [self.view addSubview:scrollView];
        
        UISwitch *sw = [[UISwitch alloc] init];
        sw.center = self.view.center;
        [scrollView addSubview:sw];
        
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [scrollView addGestureRecognizer:pan];
    }
    
    - (void)pan:(UIPanGestureRecognizer *)pan
    {
        UIView *scrollView = pan.view;
        // 获取手指偏移量
        CGPoint transPoint = [pan translationInView:pan.view];
        
        // 滚动范围
        CGRect bounds = scrollView.bounds;
        bounds.origin.y -= transPoint.y;
        
        // 限制范围
        CGFloat viewY = bounds.origin.y;
        if (viewY < 0) {
            viewY = 0;
        } else if (viewY > kScreenHeight * 0.5) {
            viewY = kScreenHeight * 0.5;
        }
        
        CGRect viewBounds = scrollView.bounds;
        viewBounds.origin.y = viewY;
        scrollView.bounds = viewBounds;
        
        // 复位 还原
        [pan setTranslation:CGPointZero inView:pan.view];
    }
    

    相关文章

      网友评论

        本文标题:UIScrollView底层实现

        本文链接:https://www.haomeiwen.com/subject/szcbrftx.html