准备:
#define VIEW_WIDTH self.view.frame.size.width
#define VIEW_HEIGHT self.view.frame.size.height
@interface RootViewController ()<UIScrollViewDelegate>
@property (nonatomic, retain) UIScrollView *sv;
@end
UIScrollView 滚动视图
self.sv = [[UIScrollView alloc] initWithFrame:self.view.frame];
self.sv.backgroundColor = [UIColor redColor];
[self.view addSubview:self.sv];
[_sv release];
滚动的原因: 控件大小限制了可显示范围 如果想要显示更多的内容 需要滚动
滚动的条件: 内容大小>frame.size
内容大小
self.sv.contentSize = CGSizeMake(VIEW_WIDTH*6, VIEW_HEIGHT);
添加图片
for (NSInteger i = 1; i <= 6; i++) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*VIEW_WIDTH, 0, VIEW_WIDTH, VIEW_HEIGHT)];
图片名
NSString *name = [NSString stringWithFormat:@"S%ld.jpg", i];
imgView.image = [UIImage imageNamed:name];
[self.sv addSubview:imgView];
[imgView release];
偏移量
只要视图滚动 偏移量就会变化
只要改变偏移量 视图就会滚动
sv.contentOffset = CGPointMake(375, 0);
内边距
sv.contentInset = UIEdgeInsetsMake(100, 200, 300, 400);
整页翻动
以当前滚动视图的宽度为1页
self.sv.pagingEnabled = YES;
边缘弹动效果
self.sv.bounces = YES;
滚到顶部
每个滚动视图默认都为YES 一个页面中存在多个滚动视图时 仅开启需要滚动的视图 其他滚动视图置为NO
self.sv.scrollsToTop = YES;
是否允许滚动
self.sv.scrollEnabled = YES;
滚动条显示/隐藏
水平horizontal
self.sv.showsHorizontalScrollIndicator = NO;
垂直vertical
self.sv.showsVerticalScrollIndicator = NO;
UIPageControl
UIPageControl *page = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
page.backgroundColor = [UIColor blackColor];
添加父视图
加载self.view保证视图滑动时 依然存在
[self.view addSubview:page];
[page release];
page.numberOfPages = 6;
page.center = CGPointMake(self.view.center.x, VIEW_HEIGHT-50);
[page addTarget:self action:@selector(page:) forControlEvents:UIControlEventValueChanged];
page.tag = 1000;
视图的滚动分为两个阶段:
1.拖拽(手指在屏幕上)
2.减速(手指离开屏幕)
self.sv.delegate = self;
滚动视图功能为: 滚动/缩放
最小比例
self.sv.minimumZoomScale = 0.5;
最大比例
self.sv.maximumZoomScale = 2;
- (void)page:(UIPageControl *)page
{
当页码变化时 改变滚动视图的偏离量
375*page.currentPage当前页码对应的滚动视图偏移量
self.sv.contentOffset = CGPointMake(375*page.currentPage, 0);
[self.sv setContentOffset:CGPointMake(375*page.currentPage, 0) animated:YES];
通过动画滚动
[UIView animateWithDuration:0.5 animations:^{
self.sv.contentOffset = CGPointMake(VIEW_WIDTH*page.currentPage, 0);
}];
}