普通的 UIView 不具有滚动功能,不能显示过多的内容。UIScrollView 是一个可以滚动的视图控件,可用来展现大量的内容。html
UIScrollView 的简单使用:atom
1)将须要展现的内容添加到 UIScrollView 中;spa
2)设置 UIScrollView 的 contentSize 属性,指定可滚动的范围。code
可用属性:htm
1) @property(nonatomic) CGPoint contentOffset; 表示 UIScrollView 滚动的位置。blog
2) @property(nonatomic) CGSize contentSize; 表示 UIScrollView 的滚动范围。开发
3) @property(nonatomic) UIEdgeInsets contentInset; 在 UIScrollView 的四周增长额外的滚动区域。get
4) @property(nonatomic) BOOL bounces; 设置 UIScrollView 是否须要弹簧效果。博客
5) @property(nonatomic, getter=isScrollEnabled) BOOL scrollEnabled; 设置 UIScrollView 是否能滚动。it
6) @property(nonatomic) BOOL showsHorizontalScrollIndicator; 是否显示水平滚动条。
7) @property(nonatomic) BOOL showsVerticalScrollIndicator; 是否显示垂直滚动条。
以下为几个属性表明的坐标示意图:
1) UIScrollView 的 frame 指可视范围, contentSize 是滚动范围。
2) contentSize 属性只能使用代码设置。
实例演示:
新建一个Single View Application,在 ViewController 类扩展中添加一个私有的 UIScrollView 属性,代码以下:
1 //ViewController.m 2 @interface ViewController () 3 { 4 UIScrollView *_scrollView; 5 } 6 @end
修改 viewDidLoad 方法,实现 UIScrollView 的添加与显示:
1 //ViewController.m 2 - (void)viewDidLoad { 3 [super viewDidLoad]; 4 //建立UIScrollView 5 UIScrollView *scrollView = [[UIScrollView alloc] init]; 6 scrollView.frame = CGRectMake(0, 0, 250, 250); 7 scrollView.backgroundColor = [UIColor grayColor]; 8 [self.view addSubview:scrollView]; 9 10 //建立UIImageView 11 UIImageView *imageView = [[UIImageView alloc] init]; 12 imageView.image = [UIImage imageNamed:@"picture.jpg"]; 13 CGFloat imageWidth = imageView.image.size.width; 14 CGFloat imageHeight = imageView.image.size.height; 15 imageView.frame = CGRectMake(0, 0, imageWidth, imageHeight); 16 [scrollView addSubview:imageView]; 17 18 //设置UIScrollView的属性 19 scrollView.contentSize = imageView.image.size; 20 scrollView.showsHorizontalScrollIndicator = YES; 21 scrollView.showsVerticalScrollIndicator = YES; 22 scrollView.contentInset = UIEdgeInsetsMake(20, 20, 20, 20); 23 _scrollView = scrollView; 24 }- (void)viewDidLoad { 25 [super viewDidLoad]; 26 //建立UIScrollView 27 UIScrollView *scrollView = [[UIScrollView alloc] init]; 28 scrollView.frame = CGRectMake(0, 0, 250, 250); 29 scrollView.backgroundColor = [UIColor grayColor]; 30 [self.view addSubview:scrollView]; 31 32 //建立UIImageView 33 UIImageView *imageView = [[UIImageView alloc] init]; 34 imageView.image = [UIImage imageNamed:@"picture.jpg"]; 35 CGFloat imageWidth = imageView.image.size.width; 36 CGFloat imageHeight = imageView.image.size.height; 37 imageView.frame = CGRectMake(0, 0, imageWidth, imageHeight); 38 [scrollView addSubview:imageView]; 39 40 //设置UIScrollView的属性 41 scrollView.contentSize = imageView.image.size; 42 scrollView.showsHorizontalScrollIndicator = YES; 43 scrollView.showsVerticalScrollIndicator = YES; 44 scrollView.contentInset = UIEdgeInsetsMake(20, 20, 20, 20); 45 _scrollView = scrollView; 46 }