#import "HYViewController.h"
#define HYpageCount 5
@interface HYViewController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/** 定時器屬性*/
@property(nonatomic,strong) NSTimer *timer;
@end
@implementation HYViewController
/** 控制器的view加載完畢的時候調用*/
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat imageW=self.scrollView.frame.size.width;
CGFloat imageH=self.scrollView.frame.size.height;
CGFloat imageY=0;
for(int i=0;i<HYpageCount;i++)
{
UIImageView *imageView=[[UIImageView alloc]init];
NSString *name=[NSString stringWithFormat:@"img_0%d",i+1];
imageView.image =[UIImage imageNamed:name];
CGFloat imageX= i*imageW;
imageView.frame=CGRectMake(imageX, imageY, imageW, imageH);
[self.scrollView addSubview:imageView];
}
self.scrollView.contentSize=CGSizeMake(HYpageCount*imageW, 0);
self.scrollView.showsHorizontalScrollIndicator=NO;
self.scrollView.pagingEnabled=YES;
self.pageControl.numberOfPages=HYpageCount;
self.scrollView.delegate=self;
[self addTimer];
}
/** 添加定時器*/
-(void)addTimer
{
self.timer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
}
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
/** 移除定時器*/
-(void)removeTimer
{
[self.timer invalidate ];
self.timer=nil;
}
/** 當用戶開始拖拽的時候調用*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self removeTimer];
}
/** 用戶徹底中止拖拽的時候調用*/
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self addTimer];
}
/** 上面的問題解決方法*/
-(void)nextPage
{
int page=0;
if(self.pageControl.currentPage==HYpageCount-1)
{
page=0;
}
else
{
page=self.pageControl.currentPage+1;
}
CGFloat offsetW=self.scrollView.frame.size.width;
CGFloat offsetX=page*offsetW;
CGPoint offset=CGPointMake(offsetX, 0);
[self.scrollView setContentOffset:offset animated:YES];
}
#pragma mark -代理方法
/** * 當scrollview正在滾動的時候就會調用 * * @param scrollView */
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat scrollW=self.scrollView.frame.size.width;
int page=self.scrollView.contentOffset.x/scrollW;
self.pageControl.currentPage=page;
}
@end
!當出現兩個點來回切換的問題的解決方案
!當用戶用手拖拽的時候,中止後,加速跑動的問題
java