UIScrollView 类为展示内容比应用程序窗口大的视图提供支持。它允许用户通过触控手势卷起内容并且通过捏合手势放大缩小内容。
- iOS 控件详解之 UIScrollView
Tips
UIScrollViewIndicatorStyle 指示器样式,指的是类似于 web 页面上的滚动条样式。
// 设置指示器(滚动条)样式
self.scrollerView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
// 加载时闪一下指示器(滚动条)
[self.scrollerView flashScrollIndicators];
在 UIScrollView 中放一张 2 倍于窗口大小的视图
视图层次:根视图控制器中添加 UIScrollView ,UIScrollView 中添加 HyponsisView 视图。
实现方法:覆盖 UIViewController 中的 loadView 方法,创建视图层次结构。
- (void)loadView {
//创建一个超大视图
CGRect screenRect = CGRectMake(0, 0, 414, 736);
//创建一个 UIScrollView 对象,将其尺寸设置为窗口大小
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:screenRect];
self.view = scrollView;
//HyponsisView的视图大小是窗口的2倍
CGRect bigRect = screenRect;
bigRect.size.width *= 2.0;
bigRect.size.height *= 2.0;
//创建一个有着超大尺寸的 HQLHypnosisView 对象并将其加入 UIScrollView 对象
HQLHypnosisView *hyponsisView = [[HQLHypnosisView alloc]initWithFrame:bigRect];
[scrollView addSubview:hyponsisView];
//告诉 UIScrollView 对象“取景”范围有多大
scrollView.contentSize = bigRect.size;
}
在 UIScrollView 中放左右两张视图
UIScrollView 对象的分页实现原理是:UIScrollView 对象会根据其 bounds 的尺寸,将 contentSize 分割为尺寸相同的多个区域。拖动结束后,UIScrollView 实例会自动滚动并只显示其中的一个区域。
同样覆盖 loadView 方法创建视图层次结构:
//创建两个 CGRect 结构分别作为 UIScrollView 对象和 HQLHypnosisView 对象的 frame
CGRect screenRect = CGRectMake(0, 0, 414, 736);
//创建一个 UIScrollView 对象,将其尺寸设置为窗口大小
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:screenRect];
//设置UIScrollView 对象的“镜头”的边和其显示的某个视图的边对齐
[scrollView setPagingEnabled:YES];
self.view = scrollView;
CGRect bigRect = screenRect;
bigRect.size.width *= 2.0;
//创建一个大小与屏幕相同的 HQLPictureView 对象并将其加入 UIScrollView 对象
HQLPictureView *pictureView = [[HQLPictureView alloc]initWithFrame:screenRect];
[scrollView addSubview:pictureView];
//创建第二个大小与屏幕相同的 HQLHypnosisView 对象并放置在第一个 HQLPictureView 对象的右侧,使其刚好移除屏幕外
screenRect.origin.x +=screenRect.size.width;
HQLHypnosisView *anotherView = [[HQLHypnosisView alloc]initWithFrame:screenRect];
[scrollView addSubview:anotherView];
//告诉 UIScrollView 对象“取景”范围有多大
scrollView.contentSize=bigRect.size;