注:本文只是本人學(xué)習(xí)的記錄。如有錯(cuò)誤的地方請(qǐng)大佬糾正堪唐、如涉嫌抄襲請(qǐng)聯(lián)系我刪除缕探,謝謝!
原理:UIScrollView
繼承于UIView
唆铐,通過(guò)添加手勢(shì)來(lái)改變bounds.origin
的位置來(lái)實(shí)現(xiàn)滾動(dòng)的效果哲戚。
提到這里我們可以來(lái)區(qū)分一下bounds
與frame
的區(qū)別
bounds
:根據(jù)自身的坐標(biāo)系來(lái)設(shè)置位置和大小,當(dāng)我們改變父視圖的bounds.origin
時(shí)會(huì)發(fā)現(xiàn)父視圖沒(méi)有變化或链,但子視圖的位置卻發(fā)生了改變.
frame
:根據(jù)父視圖的坐標(biāo)系來(lái)設(shè)置位置和大小惫恼。
滑動(dòng)
上線滑動(dòng)實(shí)際是我們改變父視圖的bounds.origin.y
、左右滑動(dòng)我們只需要改變父視圖的bounds.origin.x
澳盐,子視圖中的試圖就會(huì)出現(xiàn)滑動(dòng)的效果祈纯。讓我們用代碼來(lái)說(shuō)話吧:
#import "ZYScrollView.h"
@implementation ZYScrollView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self){
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
[self addGestureRecognizer:pan];
}
return self;
}
- (void)panAction:(UIPanGestureRecognizer *)pan {
switch (_type) {
case ScrollViewUpandDown:{//上下滑動(dòng)(我們只需要獲取它的Y軸偏移量)
// 獲取手指的偏移量
CGPoint transY = [pan translationInView:pan.view];
// 修改bounds
CGRect bounds = self.bounds;
bounds.origin.y -= transY.y;
self.bounds = bounds;
// 復(fù)位
[pan setTranslation:CGPointZero inView:pan.view];
break;
}
default:{//左右滑動(dòng)(我們只需要獲取它的X軸的偏移量即可)
// 獲取手指的偏移量
CGPoint transX = [pan translationInView:pan.view];
CGRect bounds = self.bounds;
bounds.origin.x -= transX.x;
self.bounds = bounds;
[pan setTranslation:CGPointZero inView:pan.view];
break;
}
}
}
具體的實(shí)現(xiàn)
#import "ScrollViewController.h"
#import "ZYScrollView.h"
@interface ScrollViewController ()
@property (nonatomic, strong) ZYScrollView * upScrollView;
@property (nonatomic, strong) ZYScrollView * aboutScrollView;
@end
@implementation ScrollViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.upScrollView = [[ZYScrollView alloc] initWithFrame:CGRectMake(0, 0, YSCREEN_WIDTH, YSCREEN_HEIGHT/2)];
self.upScrollView.type = ScrollViewUpandDown;
[self.view addSubview:self.upScrollView];
self.aboutScrollView = [[ZYScrollView alloc] initWithFrame:CGRectMake(0, YSCREEN_HEIGHT/2, YSCREEN_WIDTH, YSCREEN_HEIGHT/2)];
self.aboutScrollView.type = ScrollViewabout;
[self.view addSubview:self.aboutScrollView];
UIView * redView = [[UIView alloc] initWithFrame:CGRectMake(50, 100, 100, 100)];
redView.backgroundColor = [UIColor redColor];
[self.upScrollView addSubview:redView];
UIView * blueView = [[UIView alloc] initWithFrame:CGRectMake(50, 100, 100, 100)];
blueView.backgroundColor = [UIColor blueColor];
[self.aboutScrollView addSubview:blueView];
}
@end
這樣我們基本就完成視圖的滑動(dòng),還有很多可以改進(jìn)與優(yōu)化的地方這里只是簡(jiǎn)單的向大家展示了UIScrollView
的滑動(dòng)原理叼耙。