08
- (void)dealloc {
[_scrollView release];
[_pageControl release];
[super dealloc];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//获取滚动视图当前的偏移量
CGPoint offset = scrollView.contentOffset;
//如果在最后一张,此时往左滑动,跳转到第一张要执行的代码
if (offset.x + kWidth > scrollView.contentSize.width) {
[scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
}
if (offset.x < 0) {
[scrollView setContentOffset:CGPointMake(10 * kWidth, 0) animated:NO];
}
}
//在滚动视图停止滚动时,改变pageControl上面点的位置
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//获取滚动视图当前的偏移量
CGPoint offset = scrollView.contentOffset;
//计算偏移量与屏幕宽度的关系,也就是偏移了多少倍
NSInteger page = offset.x / kWidth;
//赋值
self.pageControl.currentPage = page - 1 < 0 ? 9 : page - 1;
}
- (void)click:(UIPageControl *)page {
self.scrollView.contentOffset = CGPointMake(kWidth * (page.currentPage + 1), 0);
}
- (void)viewDidLoad {
[super viewDidLoad];
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
_scrollView.delegate = self;
_scrollView.contentSize = CGSizeMake(11 * kWidth, kHeight);
_scrollView.contentOffset = CGPointMake(kWidth, 0);
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.pagingEnabled = YES;
// _scrollView.bounces = NO;
[self.view addSubview:_scrollView];
//在十个label添加之前添加一个与最后一张label一样的视图
UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
firstLabel.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
firstLabel.text = @"9";
firstLabel.font = [UIFont boldSystemFontOfSize:300];
firstLabel.textAlignment = NSTextAlignmentCenter;
[_scrollView addSubview:firstLabel];
[firstLabel release];
//循环创建十个label
for (int i = 0; i < 10; i ++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kWidth * (i + 1), 0, kWidth, kHeight)];
label.text = [NSString stringWithFormat:@"%d",i];
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont boldSystemFontOfSize:300];
if (i == 9) {
label.backgroundColor = firstLabel.backgroundColor;
} else {
label.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
}
[_scrollView addSubview:label];
[label release];
}
_pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(30, kHeight - 80, kWidth - 60, 40)];
_pageControl.numberOfPages = 10;
_pageControl.currentPage = 0;
_pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
_pageControl.pageIndicatorTintColor = [UIColor whiteColor];
_pageControl.backgroundColor = [UIColor redColor];
[_pageControl addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_pageControl];

浙公网安备 33010602011771号