UIScrollView轮播图,当手指放上去的时候停止播放,手指离开时开始播放。
我的实现思路是在scrollView上加一个长按手势UILongPressGestureRecognizer。
//添加长按手势
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longUiscrollView:)];
longPress.delegate = self;
[_scrollV addGestureRecognizer:longPress];
//手势方法实现
- (void)longUiscrollView:(UITapGestureRecognizer *)tap{
[self.timer invalidate];//循环终止
self.timer = nil;
//(手势完成时)手指离开时
if (tap.state == UIGestureRecognizerStateEnded) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
}
}
轮播图整个需求实现
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
NSInteger index = (self.scrollV.contentOffset.x ) / MAINSCREEN_WIDTH;
//这儿数值根据自己的需求设定
if (index < 1) {
self.scrollV.contentOffset = CGPointMake(2 * MAINSCREEN_WIDTH, 0);
}else if(index > 2){
self.scrollV.contentOffset = CGPointMake( MAINSCREEN_WIDTH, 0);
}
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
[self scrollViewDidEndDecelerating:self.scrollV];
}
//开始手动滑动时停止自动播放
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self.timer invalidate];//循环终止
self.timer = nil;
}
//结束手动滑动是开始自动播放
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
}
- (void)nextPage{
[self.scrollV setContentOffset:CGPointMake(self.scrollV.contentOffset.x + MAINSCREEN_WIDTH,0 )animated:YES];
}
- (void)longUiscrollView:(UITapGestureRecognizer *)tap{
[self.timer invalidate];//循环终止
self.timer = nil;
//(手势完成时)手指离开时
if (tap.state == UIGestureRecognizerStateEnded) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
}
}