UIScrollView底层实现

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];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容