美文网首页
ScrollerView的底层实现

ScrollerView的底层实现

作者: CoderLNHui | 来源:发表于2017-01-12 18:23 被阅读20次

基本原理:

  • 继承自UIView,内部加了手势,之所以可以滑动,是改变了bounds,若手指向上滑动,y++,内容就会向上滑动

代码实现


#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>

@property (weak, nonatomic)  UIView *scrollView;

@property (nonatomic, assign) CGPoint offsetX;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    UIView *scrollView = [[UIView alloc] initWithFrame:self.view.bounds];

    

    [self.view addSubview:scrollView];

    

    _scrollView = scrollView;

    

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];

    [scrollView addGestureRecognizer:pan];

    

    UISwitch *switchV = [[UISwitch alloc] init];

    

    [scrollView addSubview:switchV];

    

    

}

// 拖动的时候调用

- (void)pan:(UIPanGestureRecognizer *)pan

{

    // 获取偏移量

    CGPoint transP = [pan translationInView:pan.view];

    

    _offsetX.x += -transP.x;

    _offsetX.y += -transP.y;

    

    _scrollView.bounds = CGRectMake(_offsetX.x, _offsetX.y, self.view.bounds.size.width, self.view.bounds.size.height);

    

    [pan setTranslation:CGPointZero inView:pan.view];

    

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

    NSLog(@"%f %f",scrollView.contentOffset.y,scrollView.bounds.origin.y);

}

相关文章

网友评论

      本文标题:ScrollerView的底层实现

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