#import "QHMainController.h"
@interface QHMainController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property(nonatomic,strong) NSTimer *timer;
@end
@implementation QHMainController
- (void)viewDidLoad {
[super viewDidLoad];
int totalPage = 5;
CGFloat btnW = self.scrollView.frame.size.width;
CGFloat btnH = self.scrollView.frame.size.height;
for (int i = 0; i < totalPage; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *name = [NSString stringWithFormat:@"ad_%02d",i];
UIImage *image = [UIImage imageNamed:name];
[btn setBackgroundImage:image forState:UIControlStateNormal];
CGFloat btnX = i*btnW;
CGFloat btnY = 0;
btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
[self.scrollView addSubview:btn];
}
_scrollView.contentSize = CGSizeMake(totalPage*btnW, btnH);
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
//设置代理有两种方式 设置
_scrollView.delegate = self;
//设置pageControl的属性
self.pageControl.numberOfPages = totalPage;
self.pageControl.currentPage = 0;
[self startTimer];
}
-(void)startTimer
{
//添加一个定时器
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
self.timer = timer;
[[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self.timer invalidate];
}
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
[self startTimer];
}
-(void)autoScroll
{
//1.得到偏移量
//2如何得大滚动的位置
int totalPage = 5;
int page = self.pageControl.currentPage >=totalPage -1?0:self.pageControl.currentPage+1;
self.scrollView.contentOffset = CGPointMake(page*self.scrollView.frame.size.width, 0);
}
//只要发生滚动就会自动调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint contentOffSet = self.scrollView.contentOffset;
int page = (contentOffSet.x + self.scrollView.frame.size.width*0.5)/self.scrollView.frame.size.width;
self.pageControl.currentPage = page;
}
-(BOOL)prefersStatusBarHidden
{
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
scrollView 循环滚动
最新推荐文章于 2024-08-14 09:00:32 发布