我们都知道UIScrollView有一种很流畅的切换效果,结合UIPageControl的辅助展示效果,就可以完成一个很不错的产品介绍功能页面。下面给大家分享iOS UIScrollView滚动视图/无限循环滚动/自动滚动功能,具体代码如下所示;
#define WIDTH [[UIScreen mainScreen] bounds].size.width
#define HEIGHT [[UIScreen mainScreen] bounds].size.height
@property (nonatomic, strong)NSTimer *timer; //定时器
@property (nonatomic, retain)NSMutableArray *arr; //放图片的数组
@property (nonatomic, retain)UIView *headerView; //tableView的表头
@property (nonatomic, retain)UIImageView *image; //图片
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UIPageControl *pageC; //页码
//设置头视图
- (void)headImage{
//图片数组
self.arr = [NSMutableArray arrayWithObjects:@"8.jpg",@"1.jpg", @"2.jpg", @"3.jpg", @"4.jpg", @"5.jpg", @"6.jpg", @"7.jpg", @"8.jpg", @"1.jpg", nil];
self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200 * HEIGHT/667)];
self.scrollView.backgroundColor = [UIColor clearColor];
//设置滚动量
self.scrollView.contentSize = CGSizeMake(WIDTH * self.arr.count, 0);
//设置偏移量
self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
//设置按页滚动
self.scrollView.pagingEnabled = YES;
//设置是否显示水平滑动条
self.scrollView.showsHorizontalScrollIndicator = NO;
//设置是否边界反弹
self.scrollView.bounces = NO;
//把scrollView添加到tableView的表头的视图上
[self.headerView addSubview:self.scrollView];
[_scrollView release];
//循环图片添加到UIImageView上
for (int i = 0 ; i < self.arr.count; i++) {
NSString *name = [self.arr objectAtIndex:i];
UIImage *img = [UIImage imageNamed:name];
self.image = [[UIImageView alloc]init];
self.image.frame = CGRectMake(i * WIDTH, 0, WIDTH, 200 * HEIGHT/667);
self.image.image = img;
[self.scrollView addSubview:self.image];
[_image release];
}
self.scrollView.delegate = self;
//设置页面
self.pageC = [[UIPageControl alloc]initWithFrame:CGRectMake(100 * WIDTH/375, 120 * HEIGHT/667, 200* WIDTH/375, 60*HEIGHT/667)];
self.pageC.backgroundColor = [UIColor clearColor];
//把页码添加到头视图上
[self.headerView addSubview:self.pageC];
//设置页码数
self.pageC.numberOfPages = self.arr.count;
//设置选中页码的颜色
self.pageC.currentPageIndicatorTintColor = [UIColor brownColor];
//设置未选中的页码颜色
self.pageC.pageIndicatorTintColor = [UIColor grayColor];
//设置当前选中页
self.pageC.currentPage = 0;
//核心方法
[self.pageC addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
[_pageC release];
//自定义一个定时器方法
[self addTimer];
}
//定时器执行方法
- (void)change:(NSTimer *)time{
if (self.pageC.currentPage == self.pageC.numberOfPages - 1) {
self.pageC.currentPage = 0;
} else if (self.pageC.currentPage < self.pageC.numberOfPages - 1) {
self.pageC.currentPage++;
}
[self.scrollView setContentOffset:CGPointMake((self.pageC.currentPage + 1) * WIDTH, 0) animated:NO];
}
以上所述是小编给大家介绍的iOS UIScrollView滚动视图/无限循环滚动/自动滚动的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!