RootViewController.m
#import "RootViewController.h"
1.创建一个宏.
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface RootViewController ()<UIScrollViewDelegate>
@end
@implementation RootViewController
- (void)dealloc
{
[_scrollView release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
3.创建一个scrollview.
UIScrollView *scrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
scrollV.backgroundColor = [UIColor yellowColor];
[self.view addSubview:scrollV];
[scrollV release];
4.让scrollView进行滚动,这个属性很重要,只有设置了这个属性它才可以进行滚动.
// 水平滚动设置width,垂直滚动设置height.
scrollV.contentSize = CGSizeMake(WIDTH * 8 , 0);
5.按照页来进行滚动.
scrollV.pagingEnabled = YES;
6.把图片放到scrollView上.
for (NSInteger i = 1; i < 8; i++) {
// 拼接图片名
NSString *pictureName = [NSString stringWithFormat:@"h%ld.jpeg", i];
// 把图片放到imageView上
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * (i - 1), 0, WIDTH, HEIGHT)];
imageView.image = [UIImage imageNamed:pictureName];
[scrollV addSubview:imageView];
[imageView release];
}
7.在第七张图片之后再加上一个imageView,并且显示第一张的内容,注意,相应的contentSize也要进行修改.
UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 7, 0, WIDTH, HEIGHT)];
lastImageView.image = [UIImage imageNamed:@"h1.jpeg"];
[scrollV addSubview:lastImageView];
[lastImageView release];
8.关闭边界回弹效果.
scrollV.bounces = NO;
9.把水平和垂直的滚动条关闭.
scrollV.showsHorizontalScrollIndicator = NO;
scrollV.showsVerticalScrollIndicator = NO;
scrollV.tag = 1000;
10.设置代理人.
scrollV.delegate = self;
11.通过NSTimer来控制自动播放.
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changePicture) userInfo:nil repeats:YES];
}
12.实现方法.
- (void)changePicture {
// 通过tag找ScrollV.
UIScrollView *scrollView = (UIScrollView *)[self.view viewWithTag:1000];
// 通过设置偏移量,让哪一张视图显示在屏幕上.
[scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x + WIDTH, 0) animated:YES];
// 判断是否到当前的最后一张,如果到了需要把偏移量设置到第一张图片位置.
if (scrollView.contentOffset.x == WIDTH * 7) {
scrollView.contentOffset = CGPointMake(0 * WIDTH, 0);
}
13.只要一拖拽,一滚动,就会触发这个协议方法.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSLog(@"%g", scrollView.contentOffset.x);
}
14.当滑动结束,稳定之后会触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSLog(@"我被触发了");
if (scrollView.contentOffset.x == WIDTH * 7) {
scrollView.contentOffset = CGPointMake(0, 0);
}
}
}
UI_UIScrollView
最新推荐文章于 2015-10-20 20:23:28 发布